【问题标题】:Canvas mouse event and focus画布鼠标事件和焦点
【发布时间】:2012-11-28 09:32:07
【问题描述】:

我有 2 个圆圈和 1 个线条。圆圈有一个移动选项(你可以按下它们并移动)。 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();

【问题讨论】:

    标签: javascript html animation canvas mouseevent


    【解决方案1】:

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

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

    另外,它不会在每次鼠标移动时计算到每个点的距离,所以会更快。

    【讨论】:

    • 我有一个问题——为什么搬家是假的?例如,为什么不为空?有什么区别吗?
    • 这是一种习惯,但 null 会起作用,真的。我认为 false 更明确一点,但这只是我的意见。
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 2015-11-03
    相关资源
    最近更新 更多