试图使用4IF语句在画布x&y轴的正方向和负向上动画对象。有件事(我对JS并不熟悉)就是为什么我在负x&y轴的动画上有问题,也就是当我注释掉沿x轴的第四个if语句负运动是可能的,但是当它的活动时不能工作。
我猜想,if语句中的条件有问题。但此刻我一无所知。
http://pastebin.com/8ECXG4n0
发布于 2015-09-29 14:54:38
主要的缺陷是,由于旋转,必须使用方向大小,在这种情况下,这总是宽度。对于当前的大小,这并不明显,如果宽度与高度不同,就会看到结果(在下面的示例中,我已经更改了测试的尺寸)。
技巧2是在改变方向后折断x/y位置,因为这样高度就变宽了,反之亦然。
x += dirX * multiplier;
y += dirY * multiplier;
var margin = 10;
if(dirX > 0 && x > cW - margin - width){
degree = 90; dirX = 0; dirY = 1;
x = cW - margin;
}
else if(dirY > 0 && y > cH - margin - width){
degree = 180; dirX = -1; dirY = 0;
y = cH - margin;
}
else if(dirX < 0 && x < margin + width){
degree = 270; dirX = 0; dirY = -1;
x = margin;
}
else if(dirY < 0 && y < margin + width){
degree = 0; dirX = 1; dirY = 0;
y = margin;
}完整代码示例(代码的其余部分不变,除了一些宽度和高度的切换以改变形状):
var canvas, ctx, x, y, dir, width, height, radius, height_rect, degree, dirX, dirY;
function anim() {
var multiplier = 3;
var cW = canvas.width;
var cH = canvas.height;
width = 100;
height = 60;
radius = height / 2;
height_rect = width - radius;
ctx.clearRect(0, 0, cW, cH);
ctx.fillStyle = "magenta";
ctx.strokeStyle = "magenta";
ctx.lineWidth = 1;
ctx.save();
ctx.translate(x, y);
ctx.rotate(degree * Math.PI / 180);
ctx.translate(-x, -y);
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + height_rect, y);
ctx.arc(x + height_rect, y + radius, radius, - Math.PI / 2, Math.PI / 2);
ctx.lineTo(x, y + height);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
x += dirX * multiplier;
y += dirY * multiplier;
var margin = 10;
if(dirX > 0 && x > cW - margin - width){
degree = 90; dirX = 0; dirY = 1;
x = cW - margin;
}
else if(dirY > 0 && y > cH - margin - width){
degree = 180; dirX = -1; dirY = 0;
y = cH - margin;
}
else if(dirX < 0 && x < margin + width){
degree = 270; dirX = 0; dirY = -1;
x = margin;
}
else if(dirY < 0 && y < margin + width){
degree = 0; dirX = 1; dirY = 0;
y = margin;
}
requestAnimationFrame(anim);
}
function init() {
canvas = document.getElementById("cvsAnim");
ctx = canvas.getContext("2d");
x = 10; y = 10; dirX = 1; dirY = 0;
degree = Math.PI / 2;
anim();
}
init();canvas{
border: 1px solid;
}<canvas id="cvsAnim" width="400" height="400" style="background-color:"black">
<div id="animBox"></div>
https://stackoverflow.com/questions/32843242
复制相似问题