var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var points = []; var size = 10; var prevX = 0; var prevY = 0; var isCanDraw = false; var rect = canvas.getBoundingClientRect(); $("#canvas").on("mousedown", function(e) { isCanDraw = true; prevX = e.clientX; prevY = e.clientY; points.push({ x: prevX, y: prevY, size: size, mode: "begin" }); ctx.beginPath(); ctx.arc(prevX, prevY, size/2, 0, Math.PI*2); ctx.fill(); }); $("#canvas").on("mousemove", function(e) { if (isCanDraw) { stroke(e.clientX - rect.left, e.clientY - rect.top); points.push({ x: prevX, y: prevY, size: size, mode: "draw" }); } }); $("#canvas").on("mouseup", function(e) { isCanDraw = false; points.push({ x: prevX, y: prevY, size: size, mode: "end" }); }); $("#canvas").on("mouseleave", function(e) { isCanDraw = false; }); $("#undo").on("click", function(e) { deleteLast(); redraw(); }); function deleteLast() { if (points.length != 0) { var i = points.length - 1; while (points[i].mode != "begin") { i--; points.pop(); } points.pop(); } } function redraw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.lineCap = "round"; ctx.beginPath(); for (var i = 0; i < points.length; i++) { var pt = points[i]; switch (pt.mode) { case "begin": ctx.moveTo(pt.x, pt.y); case "draw": ctx.lineTo(pt.x, pt.y); case "end": ctx.stroke(); } } } function stroke(x, y) { ctx.lineWidth = size; ctx.lineJoin = "round"; ctx.beginPath(); ctx.moveTo(prevX, prevY); ctx.lineTo(x, y); ctx.closePath(); ctx.stroke(); prevX = x; prevY = y; }
#canvas { border: 1px solid #000; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <canvas id="canvas" width="500" height="300"></canvas> <input type="button" id="undo" value="undo">