<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");//获取input[type=color]
c1.onchange=function(){//当input[type=color]颜色改变时触发(用于更改画笔颜色)
ctx.beginPath();//防止之前画好的部分受后面画的影响
ctx.strokeStyle=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.moveTo(lastX,lastY);//最开始的起笔位置,x轴坐标,y轴坐标
ctx.lineTo(ev.offsetX,ev.offsetY);////设置终点坐标
ctx.stroke();//描边
lastX=ev.offsetX;//每次的终点坐标,即下次起笔的起点坐标(鼠标的当前位置),
lastY=ev.offsetY;//每次的终点坐标,即下次起笔的起点坐标(鼠标的当前位置)
}
document.onmouseup=function(ev){//在整个document内松开鼠标
OC.onmousemove=null;//onmousemove置空
OC.onmouseup=null;//onmouseup置空
}
}
}
</script>
<body>
<input type="color" id="c1"><br />
<canvas id="cans" height="800" width="1200">该浏览器不支持canvas元素操作,请更新浏览器</canvas>
</body>