HTML部分:
<canvas id="myCanvas"></canvas>
JavaScript部分:
var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var isDrawing = false; var startX, startY; // 监听鼠标按下事件 canvas.addEventListener("mousedown", function(e) { startX = e.clientX - canvas.offsetLeft; startY = e.clientY - canvas.offsetTop; isDrawing = true; }); // 监听鼠标移动事件 canvas.addEventListener("mousemove", function(e) { if (!isDrawing) { return; } var x = e.clientX - canvas.offsetLeft; var y = e.clientY - canvas.offsetTop; context.beginPath(); context.moveTo(startX, startY); context.lineTo(x, y); context.stroke(); startX = x; startY = y; }); // 监听鼠标松开事件 canvas.addEventListener("mouseup", function(e) { isDrawing = false; });
联系客服