什么叫橡皮筋式

指画图时橡皮筋一样伸缩自如。。
例子如下?
图片描述

思路

思路很简单,只有橡皮筋式绘制功能要注意,以下总结mousedown,mousemove,mouseup三个阶段的思路
mousedown:记录start位置,drag(记录是否处于拖动状态)设置为true,getImageData(橡皮筋效果关键1)
mousemove:获取拖动时的位置pos,putImageData(对应getImageData,橡皮筋效果关键2),根据pos与start画直线
mouseup:drag恢复为false
关键就在于putImageData()与getImageData()这两个canvas的方法,putImageData()记录了鼠标点下时的图像,getImageData()对应还原。如果没有执行这两个方法就会出现以下的效果
图片描述
putImageData()相当于把“扫描”出来的线都擦掉

代码

    <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()获取元素位置
            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>

Jonithan
249 声望12 粉丝

GitHub:[链接]