This article brings you an introduction to the canvas rubber band line drawing method (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
What is the rubber band style?
means that the rubber band can stretch freely when drawing. .
The example is as follows
##The idea
The idea is very simple, only the rubber band drawing function should be paid attention to, as follows Summarize the ideas of the three stages of mousedown, mousemove, and mouseupmousedown: record the start position, drag (record whether it is in the drag state) is set to true, getImageData (rubber band effect key 1)
mousemove: get the drag time Position pos, putImageData (corresponding to getImageData, rubber band effect key 2), draw a straight line according to pos and start
mouseup: drag is restored to false
The key 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 effect will occur
Code
<canvas> </canvas> <script> let canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'), canvasLeft = canvas.getBoundingClientRect().left, //getBoundingClientRect()获取元素位置 canvasTop = canvas.getBoundingClientRect().top; let imageData; //记录图像数据 let start = new Map([['x',null],['y',null]]); let drag = false;//记录是否处于拖动状态 canvas.onmousedown = function (e) { let pos = positionInCanvas(e, canvasLeft, canvasTop); start.set('x', pos.x); start.set('y', pos.y); drag = true; //记录imageData imageData = ctx.getImageData(0,0,canvas.width,canvas.height); } canvas.onmousemove = function (e) { if(drag === true){ let pos = positionInCanvas(e, canvasLeft, canvasTop); //相当于把扫描出来的线都擦掉,重新画 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) {//获取canvas中鼠标点击位置 return { x:e.clientX - canvasLeft, y:e.clientY - canvasTop } } </script>
The above is the detailed content of Introduction to canvas rubber band line drawing method (code example). For more information, please follow other related articles on the PHP Chinese website!