canvas -- the application of rubber band line drawing

Keywords: Javascript

What is rubber band

The rubber band stretches freely when drawing..
Examples are as follows

thinking

The idea is very simple. Only the rubber band drawing function should be noted. Here is a summary of the three stages of mousedown, mousemove and mouseup
mousedown: record the start position, drag (whether the record is in dragging state) is set to true, getimagedata (rubber band effect key 1)
mousemove: get the position pos and putimagedata when dragging (corresponding to getImageData, rubber band effect key 2), draw a line according to pos and start
mouseup: drag to false
The key lies in the two canvas methods putImageData() and getImageData(). putImageData() records the image when the mouse clicks, and getImageData() corresponds to restore. If these two methods are not implemented, the following effects will occur

putImageData() is equivalent to erasing all the lines "scanned"

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() get element location
            canvasTop = canvas.getBoundingClientRect().top;
        let imageData; //Record image data
        let start = new Map([['x',null],['y',null]]);
        let drag = false;//Record whether it is in 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);
               //It's equivalent to erasing all the scanned lines and redrawing them
               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>

Posted by owner on Mon, 02 Dec 2019 05:35:25 -0800