如何限制圆区域内的运动

时间:2023-03-15
本文介绍了如何限制圆区域内的运动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这可能更多是与几何相关的问题,但我试图将控制器限制在圆的区域内.我知道我必须接触 Math.sin() 和 Math.cos() 方法,但到目前为止我的尝试都没有结果.

This might be more a geometry related question, but I'm trying to constrain a controller within an area of a circle. I know I have to touch the Math.sin() and Math.cos() methods, but my attemps so far have been fruitless so far.

这里是 jsfiddle:到目前为止,我已经能够将它限制在一个看不见的正方形上.http://jsfiddle.net/maGVK/

Here is the jsfiddle: So far I've been able to constrain it to an invisible square. http://jsfiddle.net/maGVK/

推荐答案

所以在大家的帮助下,我终于能够完成这个了.

So I finally was able to complete this with a bit of everyone's help.

var pointerEl = document.getElementById("pointer");
var canvasEl = document.getElementById("canvas");
var canvas = {
    width: canvasEl.offsetWidth,
    height: canvasEl.offsetHeight,
    top: canvasEl.offsetTop,
    left: canvasEl.offsetLeft
};
canvas.center = [canvas.left + canvas.width / 2, canvas.top + canvas.height / 2];
canvas.radius = canvas.width / 2;


window.onmousemove = function(e) {
    var result = limit(e.x, e.y);
        pointer.style.left = result.x + "px";
        pointer.style.top = result.y + "px";
}

function limit(x, y) {
    var dist = distance([x, y], canvas.center);
    if (dist <= canvas.radius) {
        return {x: x, y: y};
    } 
    else {
        x = x - canvas.center[0];
        y = y - canvas.center[1];
        var radians = Math.atan2(y, x)
           return {
               x: Math.cos(radians) * canvas.radius + canvas.center[0],
               y: Math.sin(radians) * canvas.radius + canvas.center[1]
           }
        } 
    }

function distance(dot1, dot2) {
    var x1 = dot1[0],
        y1 = dot1[1],
        x2 = dot2[0],
        y2 = dot2[1];
    return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
}

你可以在这里看到结果:

You can see the result here:

http://jsfiddle.net/7Asn6/

这篇关于如何限制圆区域内的运动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何在 HTML5 画布上画一个模糊的圆圈? 下一篇:在谷歌地图上画圆弧

相关文章