javascript - Canvas 鼠标事件和焦点

标签 javascript html animation canvas mouseevent

我有 2 个圆圈和一条线。圆圈有一个移动选项(你可以按下它们并移动)。 Mousemove 事件有一个变量 distance 来计算鼠标和圆圈之间的距离。

问题是,当你将一个圈子移到另一个圈子足够近时,他们就会加入。如何避免这种情况?是否可以选择做一些重点或类似的事情?关于如何解决这个问题的任何想法(可能吗?)

My code :

var canvas = document.getElementById('myCanvas'),
    context = canvas.getContext('2d'),
    radius = 12,
    p = null,
    start = false;

    point = {
        p1: { x:100, y:250 },
        p2: { x:400, y:100 }
    }

function init() {
        return setInterval(draw, 10);
}

canvas.addEventListener('mousedown', function(e) {
    start = true;
});

canvas.addEventListener('mouseup', function(e) {
    start = false;
});

canvas.addEventListener('mousemove', function(e) {

    for (p in point) {
        if(start) {
            var 
                mouseX = e.clientX -10,
                mouseY = e.clientY -10,
                distance = Math.sqrt(Math.pow(mouseX - point[p].x, 2) + Math.pow(mouseY - point[p].y, 2));

            if (distance -10<= radius) {
                point[p].x = e.clientX -10 ;
                point[p].y = e.clientY -10 ;
            } 

        }
    }
});


function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.beginPath();
    context.moveTo(point.p1.x,point.p1.y);
    context.lineTo(point.p2.x,point.p2.y);

    context.closePath();

    context.fillStyle = '#8ED6FF';
    context.fill();
    context.stroke();

    for (p in point) {
        context.beginPath();
        context.arc(point[p].x,point[p].y,radius,0,2*Math.PI);
        context.fillStyle = 'red';
        context.fill();
        context.stroke();
    }
    context.closePath();
}

init();

最佳答案

尝试保存在您的 mousedown 事件中按下的点。

像这样:http://jsfiddle.net/cs5Sg/9/

此外,它不会在每次鼠标移动时都计算到每个点的距离,因此速度会更快。

关于javascript - Canvas 鼠标事件和焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13809945/

相关文章:

javascript - 过滤后的数组输出一个空数组。如何修复它?

javascript - Canvas 元素之后(之下)的 HTML 内容

loops - mp4 Vj 动画视频滞后于高分辨率视频

javascript - 什么时候加载谷歌地图?

javascript - 即使正则表达式显示 "don' ,如果相同的字符在前面/后面,字符仍然匹配”

javascript - WKWebview如何设置比例尺?

html - Angular 抛出 ExpressionChangedAfterItHasBeenCheckedError

c++ - GBA C++ : How to draw multiple animating pixels using arrays?

android - Galaxy Note 上的动画不流畅

javascript - 无法使用 derbyjs 在 View 中显示文档列表