<div class="wrapper">
<canvas class=cavs width="1000" height="400">canvas>
<ul class="btn-list">
<li><input type="color" id="colorBoard" value="colorboard">li>
<li><input type="button" id="cleanBoard" value="清屏">li>
<li><input type="button" id="eraser" value="橡皮">li>
<li><input type="button" id="rescind" value="撤消">li>
<li><input type="range" id="lineRuler" value="线条" min='1' max='30'>li>
ul>
div>
input元素的type类型
传统类型
新增类型
*{
margin: 0;
padding: 0;
list-style: none;
}
body{
background: url('img/xhr.jpg') no-repeat;
background-size: cover;
}
.wrapper{
margin-left: 15px;
}
.wrapper canvas{
border: 1px solid royalblue;
border-radius: 25px;
box-shadow: 10px 10px 5px #888888;
margin-bottom: 20px;
}
.wrapper .btn-list{
width: 1000px;
text-align: center;
}
.wrapper .btn-list li{
display: inline-block;
margin-left: 40px;
}
.wrapper .btn-list li input{
background: yellow;
color: #000;
border: none;
padding: 10px 20px;
cursor: pointer;
border-radius: 25px;
font-size: 20px;
display: block;
transition-duration:0.2s;
}
.wrapper .btn-list li input:hover{
border: 1px solid rebeccapurple;
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.3);
}
为了避免全局变量的污染,尽可能创建一个全局变量。让其他对象和函数存在其中。
var drawingLineObj = {
cavs: $('.cavs'),
context: $('.cavs').get(0).getContext('2d'),
colorBoard: $('#colorBoard'),
lineRuler: $('#lineRuler'),
bool: false,//锁
init: function () {
this.context.lineCap = 'round';//线条起始和结束是样式
this.context.lineJoin = 'round';//转弯
this.draw();
this.btnFun();//点击按钮事件
}
}
draw: function () {
var cavs = this.cavs,
self = this;
// 获取canvas内鼠标坐标记得减去canvas边距
var c_x = cavs.offset().left,
c_y = cavs.offset().top;
//画笔放下
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 (e) {
self.context.closePath();
self.bool = false;
});
//画笔离开
cavs.mouseleave(function (e) {
self.context.closePath();
self.bool = false;
});
})
},
btnFun: function () {
var self = this;
$('.btn-list').on('click', function (e) {
e = e || window.event;
switch (e.target.id) {//获取操作的id
case 'cleanBoard'://清屏
...
case 'eraser'://橡皮擦
...
case 'rescind'://撤消
...
}
});
}
case 'eraser'://橡皮擦
self.context.strokeStyle = '#fff';
break;
case 'cleanBoard'://清屏
self.context.clearRect(0, 0, self.cavs[0].width, self.cavs[0].height);
break;
this.colorBoard.change(function (e) {//改变画笔颜色
self.context.strokeStyle = $(this).val();
});
this.lineRuler.change(function (e) {//改变笔触
self.context.lineWidth = $(this).val();
});
在draw方法中将每一笔存储下来
//储存每一笔,撤消时将最后一笔移除数组
var imgData = self.context.getImageData(0, 0, self.cavs[0].width, self.cavs[0].height);
self.arrImg.push(imgData);
btnFun方法点击撤销将数组最后一个元素pop
case 'rescind'://撤消
if (self.arrImg.length > 0) {//小于0会报错
self.context.putImageData(self.arrImg.pop(), 0, 0);
}
break;