CANVAS ----- 鼠标移动画圆

1、增加鼠标移动事件

$('#canvas').mousemove(function (e) {
            draw(event);
        });

 

2、获取鼠标在canvas上的坐标

 function getCanvasPos(canvas, e) {//获取鼠标在canvas上的坐标
        var rect = canvas.getBoundingClientRect();
        return {
            x: e.clientX - rect.left * (canvas.width / rect.width),
            y: e.clientY - rect.top * (canvas.height / rect.height)
        };
    }

3、获取鼠标在整个页面上的坐标

    function mousePos(e) {//获取鼠标所在位置的坐标,相对于整个页面
        var x, y;
        var e = e || window.event;
        return {
            x: e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft,
            y: e.clientY + document.body.scrollTop + document.documentElement.scrollTop
        };
    }

 

 

4、画圆

  function draw(e) {
        var c = document.getElementById("can_header");
        var cxt = c.getContext("2d");
        cxt.clearRect(0, 0, c.width, c.height);
        cxt.fillStyle = "#FF0000";
        cxt.beginPath();
        //cxt.arc(mousePos(e).x,mousePos(e).y,15,0,Math.PI*2,true);
        cxt.arc(getCanvasPos(c, e).x, getCanvasPos(c, e).y, 15, 0, Math.PI * 2, true);
        cxt.closePath();
        cxt.fill();
    }

打个广告,有需要微信投票或点赞的朋友可以找我。wx:18963948278

posted @ 2020-07-19 16:48  爱生活,爱代码  阅读(795)  评论(0编辑  收藏  举报