Finger drawing can stretch like a rubber band. .
An example is as follows: point_down:
IdeasThe idea is very simple. You only need to pay attention to the rubber band drawing function. The following summarizes the ideas of the three stages of mousedown, mousemove, and mouseup.
mousedown: record the start position, drag (record whether it is in a dragging state) is set to true, getImageData ( 橡皮筋效果关键1
)
mousemove: Get the position pos when dragging, putImageData ( 对应getImageData,橡皮筋效果关键2
), draw a straight line according to pos and start
mouseup:drag reverts to false
关键
lies in the two canvas methods putImageData() and getImageData(). putImageData() records the image when the mouse is clicked, and getImageData() restores it accordingly. If these two methods are not executed, the following effects will occur:
putImageData() is equivalent to erasing all the scanned lines
code
<canvas id=canvas width=600 height=400 style=border: 1px solid black;> </canvas> <script type=text/javascript> let canvas = document.getElementById('canvas'), ctx = canvas.getContext( '2d'), canvasLeft = canvas.getBoundingClientRect().left, //getBoundingClientRect() gets the element position canvasTop = canvas.getBoundingClientRect().top; let imageData; //Record image data let start = new Map([['x',null],['y',null]]); let drag = false; //Record whether In the dragging state canvas.onmousedown = function (e) { let pos = positionInCanvas(e, canvasLeft, canvasTop); start.set('x', pos.x); start.set('y', pos.y); drag = true; //Record imageData imageData = ctx.getImageData(0,0,canvas.width,canvas.height); } canvas.onmousemove = function (e) { if(drag === true) { let pos = positionInCanvas(e, canvasLeft, canvasTop); //Equivalent to erasing all the scanned lines and redrawing ctx.putImageData(imageData, 0, 0); ctx.beginPath(); ctx.moveTo(start.get('x'), start.get('y')); ctx.lineTo(pos.x, pos.y); ctx.stroke() ; } } canvas.onmouseup = function (e) { drag = false; } function positionInCanvas (e, canvasLeft, canvasTop) {//Get the mouse click position in canvas return { x:e.clientX - canvasLeft, y:e.clientY - canvasTop } } </script>
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.