html部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="canvas.css">
<!-- <link rel="stylesheet" href="../二级菜单/reset.css"> -->
</head>
<body>
<div id="conter">
<canvas id="canvas" width="600" height="300"></canvas>
<ul>
<li><input type="color" id="colorBoard" value="#000000"></li>
<li><input type="button" id="clear" value="清屏"></li>
<li><input type="button" id="rubber" value="橡皮"></li>
<li><input type="button" id="concel" value="撤销"></li>
<li><input type="range" id="line" value="1" min="1" max="30"></li>
</ul>
</div>
<!-- <script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> -->
<script src="canvas.js"></script>
</body>
</html>
css部分
#canvas{
border: 1px solid cyan;
margin: 20px;
box-shadow: 10px 10px 8px #ccc;
border-radius: 20px;
}
ul{
width: 600px;
text-align: center;
height: 40px;
}
ul li{
display: inline-block;
}
#clear,#rubber,#concel{
display: block;
padding: 3px 10px;
background-color: rgb(226, 198, 126);
border-radius: 12px;
margin: 0 10px;
}
#colorBoard{
background-color: rgb(247, 223, 165);
border: none;
padding: 3px 6px;
}
#clear:hover,#rubber:hover,#concel:hover{
box-shadow: 5px 5px 3px #ccc;
}
新手用原生js写的,没在对象里面写,用的都是新手的思路写的,就连一些this我也没引用,直接调用的,希望对新手有用。(我的想法是先把js写熟悉了,再考虑优化)
原生js部分:
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
//设置锁
var bool=false;
var clickColor=document.getElementById('colorBoard');
var line=document.getElementById('line');
var clear=document.getElementById('clear');
var rubber=document.getElementById('rubber');
var concel=document.getElementById('concel');
var arr=[];
//使绘画开头变成圆形
ctx.lineCap='round';
//使绘画转弯变为圆形
ctx.lineJoin="round";
//鼠标按下记录起始坐标
canvas.onmousedown=function(e){
bool=true;
var ev=e||window.event;
var cavs=ctx;
var z_x=ev.offsetX,//获取鼠标在画布内的位置
z_y=ev.offsetY;
cavs.beginPath();
cavs.moveTo(z_x,z_y);
//鼠标移动,开始绘制
canvas.onmousemove=function(e){
if(bool){
var ev=e||window.event;
var s_x=ev.offsetX,//移动时获取实时位置
s_y=ev.offsetY;
cavs.lineTo(s_x,s_y);
cavs.stroke();
}
}
//鼠标抬起,绘制结束
canvas.onmouseup=function(){
cavs.closePath();
bool=false;
}
//鼠标移出画布,绘制结束
canvas.onmouseleave=function(){
cavs.closePath();
bool=false;
}
//截取每次绘制后的画布,并存入数组里面
var imgData=cavs.getImageData(0,0,canvas.width,canvas.height);
arr.push(imgData);
}
//改变画笔颜色
clickColor.addEventListener('change',function(){
ctx.strokeStyle=this.value;
})
//改变画笔大小
line.addEventListener('change',function(){
ctx.lineWidth=this.value;
})
//点击清空屏幕
clear.addEventListener('click',function(){
ctx.clearRect(0,0,canvas.width,canvas.height);
})
//点击抹掉画笔所画部分
rubber.addEventListener('click',function(){
ctx.strokeStyle='#ffffff';
})
//点击返回上一步
concel.addEventListener('click',function(){
//画布变为删除最后面一步的画面
ctx.putImageData(arr.pop(),0,0);
})