canvas---绘制图表以及拖拽

1.clientX、offsetX、screenX、pageX、x的区别

  • clientX、clientY:点击位置距离当前body可视区域的x,y坐标
  • pageX、pageY:对于整个页面来说,包括了被卷去的body部分的长度
  • screenX、screenY:点击位置距离当前电脑屏幕的x,y坐标
  • offsetX、offsetY:相对于带有定位的父盒子的x,y坐标
  • x、y:和screenX、screenY一样 
2.设置canvas容器
 <div style="position:relative;">
        <canvas id="can" width="500" height="500"
            style="border:1px solid yellow;position:absolute;left:100px;"></canvas>
  </div>

3.绘制canvas并进行拖拽

 

 var can = document.getElementById("can");
    var ctx = can.getContext("2d");

    //初始化一个圆
    createBlock(150, 350);
    //创建圆滑块
    function createBlock(a, b) {
        ctx.beginPath();
        line()
        ctx.beginPath();
        ctx.fillStyle = "red";
        ctx.arc(a, b, 30, 0, Math.PI * 2);
        ctx.strokeStyle = "red";
        ctx.moveTo(0, 500);
        ctx.lineTo(a, b);
        ctx.stroke();
        ctx.moveTo(100, 500);
        ctx.lineTo(a, b);
        ctx.stroke(); // Draw it
    }
    //鼠标按下,将鼠标按下坐标保存在x,y中  

    can.onmousedown = function (ev) {
        var e = ev || event;
        // var x = e.clientX;
        // var y = e.clientY;
        var x = e.offsetX;
        var y = e.offsetY;
        drag(x, y);
        // console.log(x, y)
    };
    // 画坐标表格
    function line() {
        for (var i = 1; i < 50; i++) {
            ctx.beginPath();
            ctx.lineWidth = "1";
            ctx.strokeStyle = "#000"; // Green path
            ctx.moveTo(0, (i - 1) * 10);
            ctx.lineTo(500, (i - 1) * 10);
            ctx.stroke();
            i = i + 5
        }
        for (var i = 1; i < 50; i++) {
            ctx.beginPath();
            ctx.lineWidth = "1";
            ctx.strokeStyle = "#000"; // Green path
            ctx.moveTo((i - 1) * 10, 0);
            ctx.lineTo((i - 1) * 10, 500);
            ctx.stroke();
            i = i + 5
        }
    };
    //拖拽函数
    function drag(x, y) {
        // 按下鼠标判断鼠标位置是否在圆上,当画布上有多个路径时,isPointInPath只能判断最后那一个绘制的路径
        // sPointInPath判断点是不是在路径中
        // 如果鼠标的坐标x,y是在圆上,则拖动
        if (ctx.isPointInPath(x, y)) {
            // console.log(x, y)
            //路径正确,鼠标移动事件
            ctx.beginPath();
            can.onmousemove = function (ev) {
                var e = ev || event;
                // var ax = e.clientX;
                // var ay = e.clientY;
                var ax = e.offsetX;
                var ay = e.offsetY;
                //鼠标移动每一帧都清楚画布内容,然后重新画圆
                ctx.clearRect(0, 0, can.width, can.height);
                createBlock(ax, ay);
            };
            //鼠标松开事件
            can.onmouseup = function () {
                can.onmousemove = null;
                can.onmouseup = null;
            };
        };
    }

 

 

 

 

posted @ 2020-08-28 16:53  ljygirl  阅读(457)  评论(0编辑  收藏  举报