该功能主要通过监听鼠标事件来在canvas上绘制
const cvs = document.getElementById("cvs");//获取canvas节点 const ctx = cvs.getContext("2d"); let isDrawing = false;//标记是否处于绘制状态 cvs.addEventListener("mousedown", e => {//鼠标按下时开始绘制,并将画笔移动到鼠标按下位置 isDrawing = true; ctx.moveTo(e.pageX, e.pageY) }) cvs.addEventListener("mousemove", e => {//鼠标移动时,绘制移动路径 if (isDrawing) { ctx.lineTo(e.pageX, e.pageY); ctx.stroke() } }) cvs.addEventListener("mouseup", e => {//松开鼠标后,取消绘制状态 isDrawing = false; }) function Clear() {//重置canvas宽高来进行清除绘制内容 cvs.width = cvs.width; cvs.height = cvs.height; }
标签:canvas,20,鼠标,ctx,cvs,js,手写,isDrawing,绘制 From: https://www.cnblogs.com/wen-web/p/16748027.html