js 画线条,支持PC端与触摸屏端

由 夕空 撰写于  2021年10月24日
/*
new lineCanvas({
canvas: canvas,
lineWidth: 9, // 线条粗细
color: '#000000', // 线条颜色
// background: '#fff'
});
*/
function lineCanvas(obj) {
if ('ontouchstart' in document.documentElement) {
window.thetouche = true;
}
this.lineWidth = 5;
this.color = '#000000';
this.background = 'transparent';
for (var i in obj) {
this[i] = obj[i];
};

this.cxt = this.canvas.getContext('2d');
this.cxt.fillStyle = this.background;
this.cxt.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.cxt.strokeStyle = this.color;
this.cxt.lineWidth = this.lineWidth;
this.cxt.lineCap = 'round'; // 线条末端添加圆形线帽,减少线条的生硬感
this.cxt.lineJoin = 'round'; // 线条交汇时为原型边角
// 利用阴影,消除锯齿
this.cxt.shadowBlur = 1;
this.cxt.shadowColor = this.color||'#000000';
var offset=this.canvas.getBoundingClientRect();

var than=this;
// 开始绘制
this.canvas.addEventListener('mousedown', drawStart, false);
this.canvas.addEventListener('touchstart', drawStart, false);
function drawStart(e) {
if(window.thetouche && !e.targetTouches){
return;
}else if(!e.targetTouches){
than.canvas.addEventListener('mousemove', drawMove, false);
}
var touch = e.targetTouches ? e.targetTouches[0] : e;

signstart=true;
than.cxt.beginPath();
than.cxt.moveTo(touch.pageX-offset.left, touch.pageY-offset.top);
}

// 绘制中
this.canvas.addEventListener('touchmove', drawMove, false);
function drawMove(e) {
var touch = e.targetTouches ? e.targetTouches[0] : e;
than.cxt.lineTo(touch.pageX-offset.left, touch.pageY-offset.top);
than.cxt.stroke();
}

// 结束绘制
this.canvas.addEventListener('mouseup', drawEnd, false);
this.canvas.addEventListener('mouseleave', drawEnd, false);
this.canvas.addEventListener('touchend', drawEnd, false);
function drawEnd(e) {
if(window.thetouche && !e.targetTouches){
return;
}else if(!e.targetTouches){
than.canvas.removeEventListener('mousemove', drawMove, false);
}
than.cxt.closePath();
}

// 清除画布
// this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);

}

如果需要笔锋粗细变化,可以下载这个github:

https://github.com/szimek/signature_pad

声明:星耀夕空|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - js 画线条,支持PC端与触摸屏端


欢迎光顾我的小站!