# 签名手写

返回:js 进阶

问题

  • 如何用 canvas 做笔迹跟随?
  • 有没有第三方签名插件?
  • 横竖屏切换问题?

# 创建 canvas 画布及画笔样式

const canvasEl = document.createElement('canvas');
const ctx = canvasEl.getContext('2d');
const rootEl = document.getElementById('signature')
rootEl.appendChild(canvasEl)

ctx.strokeStyle = '#000';
ctx.lineWidth = 5
1
2
3
4
5
6
7

# 定义“画笔”事件

首先,结合 getBoundingClientRect 能获取画笔在画布中的坐标值

const getPoint = e => {
    const touches = e.touches[0]
    const rect = canvasEl.getBoundingClientRect()
    const x = touches.clientX - rect.left
    const y = touches.clientY - rect.top
}
1
2
3
4
5
6

根据画笔绘制过程,拆分为三个状态:开始绘制(记录 canvas 起始点),笔迹跟随,绘制完成(事件释放)

const startSign = e => {
    ctx.beginPath.apply(ctx, getPoint(e))
    canvasEl.addEventListener('touchmove', drawSign, false)
    canvasEl.addEventListener('touched', moveSign, false)
}

const moveSign = e => {
    ctx.closePath()
    canvasEl.addEventListener('touchmove', drawSign, false)
    canvasEl.addEventListener('touchmove', moveSign, false)
}

const drawSign = e => {
    const point = getPoint(e)
    ctx.lineTo.apply(ctx, point)
    cxt.stroke()
}

canvasEl.addEventListener('touchstart', startSign, false)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# jSignature

它依赖 jQuery ,对于不支持 canvas 的浏览器有降级处理,同时对笔迹绘制,图形导出有优化