我想制作一个应用程序,让球按照鼠标击中它的 Angular 移动。因此,如果您从左上象限以 30 度 Angular 向下滑动鼠标(我猜那将是 180-30 = 150 度 Angular ),它会以这种方式击球。我一直在这样画我的线条:
function drawAngles () {
var d = 50; //start line at (10, 20), move 50px away at angle of 30 degrees
var angle = 80 * Math.PI/180;
ctx.beginPath();
ctx.moveTo(300,0);
ctx.lineTo(300,600); //x, y
ctx.moveTo(0,300);
ctx.lineTo(600,300);
ctx.moveTo(300,300);
ctx.lineTo(600,100);
ctx.arc(300,300,300,0,2*Math.PI);
ctx.stroke();
}
但这并没有让我知道 Angular 是多少。
然后我以那个 Angular 移动球(现在,我在没有鼠标交互的情况下为其设置动画)
function getAngleX (x) {
return x = x + (50 * Math.cos(Math.PI/6));
}
function getAngleY(y) {
return y = y + (50 * Math.sin(Math.PI/6));
}
//just animate this box to move at an angle from center down at 30 degrees
$(".anotherBox").mouseenter(function(e) {
pos = $(this).position();
box2X = pos.left;
box2Y = pos.top;
$(this).animate({
//top : $(window).outerHeight(),
top : getAngleY(box2Y)+"px",
left: getAngleX(box2X)+"px",
}, "slow");
});
那么如何以指定的 Angular 画一条线呢?我想确保我的球沿着那条路走。
最佳答案
您可以使用不同的方法来实现这一点,但如果您想使用相同的基础来移动和绘制,那么这种方法可能很适合。
首先我们使用一个函数根据 Angular (以弧度为单位)获取 x 和 y 的步长值:
function getSteps(angle) {
var cos = Math.cos(angle),
sin = Math.sin(angle);
return {
x: cos -sin,
y: sin + cos
}
}
然后使用这些步进值,我们可以缩放它们以获得终点,或逐渐缩放它们以沿线为对象设置动画。一个简单的循环可能如下所示(仅作为示例):
function loop() {
var x = i * step.x, // scale using i
y = i * step.y;
ctx.fillRect(200 + x, 200 + y, 2, 2); // add to origin start point 200, 200
i += 1; // increase i
if (i < length) requestAnimationFrame(loop);
}
Live demo
如果您只想以特定 Angular 画一条线,您可以改为执行以下操作:
function lineAtAngle(x1, y1, length, angle) {
ctx.moveTo(x1, y1);
ctx.lineTo(x1 + length * Math.cos(angle), y1 + length * Math.sin(angle));
}
然后抚摸它。
希望这对您有所帮助!
关于javascript - JS Canvas - 以指定 Angular 画线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22977372/