本文实例为大家分享了javascript实现画板功能的具体代码,供大家参考,具体内容如下
画板功能的实现
*{
margin: 0;
padding: 0;
list-style: none;
}
body{
background:url(11.jpg) 0 0 no-repeat;
}
.wrapper{
margin: 10px;
}
.wrapper canvas{
border: 1px solid blue;
border-radius:25px;
box-shadow: 10px 10px 5px brown;
margin-bottom: 16px;
background-color: #fff;
}
.wrapper .btn-list{
width: 1000px;
text-align: center;
}
.wrapper .btn-list li{
display: inline-block;
margin-left: 40px;
}
.wrapper .btn-list li input{
background-color: darkgreen;
color: blanchedalmond
border: none;
padding: 6px 13px;
cursor: pointer;
border-radius:25px;
font-size: 18px;
display: block;
transition-duration: 0.2s;
}
.wrapper .btn-list li input:hover{
border: 1px solid chocolate;
box-shadow: 0 12px 15px 0 rgba(0,0,0,0.5);
}
var drawingLineObj = {
cavs:$('.cavs'),
context:$('.cavs').get(0).getContext('2d'),
colorBoard:$('#colorBoard'),
cleanBoard:$('#cleanBoard'),
arrImg:[],
eraser:$("#eraser"),
rescind:$('#rescind'),
lineRuler:$('#lineRuler'),
bool:false,
init:function(){
this.context.lineCap = 'round'; //线条起始与结尾样式
this.context.lineJoin = 'round'; //转弯
this.draw(); //画笔函数
this.btnFn(); //按钮函数
},
draw:function(){
var cavs = this.cavs,
self = this;
var c_x = cavs.offset().left, //canvas离左边的距离
c_y = cavs.offset().top; //canvas离上边的距离
cavs.mousedown(function(e){
e = e||window.event;
self.bool = true;
var m_x = e.pageX - c_x, //鼠标点距离减去canvas离左边的距离等于画布点
m_y = e.pageY - c_y; //鼠标点距离减去canvas离上边的距离等于画布点
self.context.beginPath();
self.context.moveTo(m_x,m_y);//鼠标在画布上的点
var imgData = self.context.getImageData(0,0,self.cavs[0].width,self.cavs[0].height);
self.arrImg.push(imgData);
//console.log(self.arrImg);
})
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; //鼠标不移动时画笔断开
})
},
btnFn:function(){
var self = this;
$('.btn-list').on('click',function(e){
e = e||window.event;
switch(e.target.id){ //target
case 'cleanBoard':
self.context.clearRect(0,0,self.cavs[0].width,self.cavs[0].height) //[0]
break
case 'eraser':
self.context.strokeStyle = '#fff'
break
case 'rescind':
if(self.arrImg.length>0){
self.context.putImageData(self.arrImg.pop(),0,0);
break
}
}
})
this.colorBoard.change(function(e){ //当颜色变化时改变字体的颜色
self.context.strokeStyle = $(this).val();
})
this.lineRuler.change(function(e){ //线条的变化值
self.context.lineWidth = $(this).val();
})
}
}
drawingLineObj.init();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。