canvas 画板

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body {
background: black;
text-align: center;
}
#cans {
background: white;

}
</style>
<script>
window.onload=function(){


let OC=document.getElementById("cans");
let c1=document.getElementById("c1");
let color="black";
c1.onchange=function(){ //改变画笔颜色
color=this.value; //给画笔赋值,this.value即c1改变后的颜色值
}
let ctx=OC.getContext("2d");
let lastX,lastY;
OC.onmousedown=function(ev){ //按下鼠标
lastX=ev.offsetX; //获取鼠标位置x轴坐标
lastY=ev.offsetY; //获取鼠标位置y轴坐标



OC.onmousemove=function(ev){ //在画布里按下鼠标并移动鼠标
ctx.beginPath();
ctx.moveTo(lastX,lastY);
ctx.lineTo(ev.offsetX,ev.offsetY); //设置终点坐标
ctx.strokeStyle=color;
ctx.stroke();
lastX=ev.offsetX; //每次的终点坐标,即下次起笔的起点坐标(鼠标的当前位置)
lastY=ev.offsetY; //每次的终点坐标,即下次起笔的起点坐标(鼠标的当前位置)


}

document.onmouseup=function(ev){ //在整个document内松开鼠标
OC.onmousemove=null; //置空
OC.onmouseup=null; //置空


}


}



}
</script>
</head>
<body>
<input type="color" id="c1"><br />
<canvas id="cans" height="800" width="1200">该浏览器不支持canvas元素操作,请更新浏览器</canvas>
</body>
</html>

原文地址:https://www.cnblogs.com/suga/p/8572845.html