本篇文章小编给大家分享一下html5 canvas做批改作业的小插件代码示例,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
需求分析
能进行批改,就是相当于画笔
能进行画笔的撤回功能
能进行全部画笔的清除功能
可以转化画笔的颜色
画笔的实现
当按下鼠标(mousedown)记录开始点startX, startY
当移动鼠标的时候(mousemove)就获取当前的鼠标的坐标e.cpentX,
e.cpentY,获取到了当前的坐标后,与上一个点的坐标轴的左边进行连线(pneTo ),这样就能画出了一条横线了
当鼠标松开左键(mouseup)时候,就清除mousemove的函数
清除功能:讲原始的图片再次用drawImage()函数来重置
撤回功能:在每次按下鼠标那时候,用getImageData()函数获取当前的图像记录到数组里面,然后按撤回则使用putImageData()函数放在canvas
画笔的颜色:在mousemove里面改变strokeStyle笔的颜色
代码实现
移动鼠标画出线条的代码
let self = this;
this.canvasNode = document.createElement('canvas');
let styleString = this.utils.formatStyle(CANVAS_STYLE); // CANVAS_STYLE是canvas的样式
this.canvasNode.setAttribute('id','canvas');
// 一定要设置这width 和 height
let ratio = this.imgNode.width / this.imgNode.height, height = this.imgNode.height, width = this.imgNode.width;
let tempWidth , tempHeight;
// 按比例伸缩
if(ratio >= window.innerWidth / window.innerHeight){
if(width > window.innerWidth){
tempWidth = window.innerWidth;
tempHeight = height * window.innerWidth / width;
} else {
tempWidth = width;
tempHeight = height;
}
}else{
if(height > window.innerHeight){
tempWidth = width * window.innerHeight / width;
tempHeight = window.innerHeight;
}else{
tempWidth = width;
tempHeight = height;
}
}
this.canvasNode.height = tempHeight;
this.canvasNode.width = tempWidth;
styleString = Object.assign({'width': tempWidth, 'height': tempHeight}, CANVAS_STYLE);
this.canvasNode.setAttribute('style', styleString);
let ctx = this.canvasNode.getContext('2d'), startX = 0, startY = 0;
let image = new Image() ;
image.setAttribute("crossOrigin",'Anonymous')
// 加时间戳因为这图片的域名没设置跨域https://www.jianshu.com/p/c3aa975923de
image.src = this.imgNode.src + '?t=' + new Date().getTime();
image.height = tempHeight;
image.width = tempWidth;
image.onload = function(){
ctx.drawImage(image, 0, 0, tempWidth, tempHeight);
}
// 鼠标移动事件
let mousemoveFn = function(e) {
ctx.beginPath();
ctx.lineWidth = 3;
ctx.strokeStyle = self.currentColor;
if(startX == e.clientX - self.canvasNode.offsetLeft || startY === e.clientY - self.canvasNode.offsetTop ) return
ctx.moveTo(startX,startY);
ctx.lineTo(e.clientX - self.canvasNode.offsetLeft , e.clientY - self.canvasNode.offsetTop );
ctx.stroke();
startX = e.clientX - self.canvasNode.offsetLeft;
startY = e.clientY - self.canvasNode.offsetTop ; // 37是header的高度
}
// 鼠标按下事件
this.canvasNode.addEventListener("mousedown",function(e){
startX = e.clientX - self.canvasNode.offsetLeft;
startY = e.clientY - self.canvasNode.offsetTop ;
// 如果在mouseup那里记录 则在撤回时候要做多一个步骤
let imageData = ctx.getImageData(0,0, self.canvasNode.width, self.canvasNode.height);
self.imageDataArray.push(imageData); // 这imageDataArray用来记录画笔的笔画
self.canvasNode.addEventListener("mousemove", mousemoveFn, false);
},false);
this.canvasNode.addEventListener('mouseup', function(e){
self.canvasNode.removeEventListener('mousemove', mousemoveFn);
});
this.bgNode.appendChild(this.canvasNode);