实现效果
canvas相关
- 用到的一些canvas的知识
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2); //从x1,y1绘制到x2,y2
ctx.stroke(); //描边,最后要有这个方法才能出现图像
ctx.strokeStyle = ""; //边的颜色
ctx.fill(); //填充
ctx.fillStyle = "" //填充颜色
ctx.closePath() //会自动闭合(就是会连到第一点上)
//如果用lineTo到第一点这样来闭合会不平滑,像下图这样
ctx.beginPath() //重新开始绘制
//否则画了一笔再换颜色画下一笔时会发现第一笔颜色也变了
ctx.getImageData(); //得到像素数据,也就是复制
ctx.putImageData(); //放置
ctx.clearRect(x,y,width,height); //清除画布方形区域
实现
-
html
-
js
draw函数
主要是几个鼠标事件【mousedown、mousemove、mouseup、mouseleave】
获取好坐标在 mousemove 时使用 lineTo 方法就可以画画了
draw: function(){
var cavs = this.cavs,
self = this;
//获取偏移距离
var c_x = cavs.offset().left,
c_y = cavs.offset().top;
this.context.lineCap = 'round'; //线条起始和结尾样式
this.context.lineJoin = 'round'; //转弯时的线条样式
//鼠标按下之后
cavs.mousedown(function(e){
e = e || window.event;
self.bool = true;
//减去添加的画板的边距
var m_x = e.pageX - c_x,
m_y = e.pageY - c_y;
self.context.beginPath();
self.context.moveTo(m_x,m_y); //鼠标在画布上的触点
cavs.mousemove(function(e){
//判断鼠标抬起来时是不移动的
if(self.bool){
self.context.lineTo(e.pageX-c_x, e.pageY-c_y);
self.context.stroke();
}
})
cavs.mouseup(function(){
self.context.closePath();
self.bool = false;
})
cavs.mouseleave(function(){
self.context.closePath();
self.bool = false;
})
//撤销功能,每画一笔就复制以下整个画布,将这些数据存在一个数组中
//点击一下撤销就把数组的最后一个粘贴到画布上并删除此数据
var imgData = self.context.getImageData(0,0,self.cavs[0].width,self.cavs[0].height);
self.arrImg.push(imgData);
//console.log(self.arrImg);
})
}
btnFn函数
清屏使用 clearRect 函数
橡皮将画笔颜色改为白色
撤销使用 putImageData 函数,将在 mousedown 时存在数组中的最后一项数据粘贴到画布上,可以达到撤销的效果
btnFn: function(){
var self = this;
$('.btn-list').on('click',function(e){
e = e || window.event;
switch(e.target.id){
case 'clean':
self.context.clearRect(0,0,self.cavs[0].width,self.cavs[0].height);
break;
case 'rubber':
self.context.strokeStyle = "#fff";
break;
case 'cancel':
if(self.arrImg.length>0){
self.context.putImageData(self.arrImg.pop(),0,0);
}
break;
}
})
$('#colorBoard').change(function(e){ //颜色改变,同步字体颜色
self.context.strokeStyle = $(this).val();
})
$('#wide').change(function(e){ //线条粗细
self.context.lineWidth = $(this).val();
})
}
可在 github 上获取全部代码