尝试沿画布x- &使用4个if语句在正方向和负方向上为对象设置动画效果。 (我是JS的新手)我是为什么即时通讯有问题的动画y轴的负面,也是当我注释掉第四条if语句沿x轴的消极运动是可能的,但不会工作当它活跃时。沿x轴和y轴的html5画布动画
我的猜测是if语句中的条件有问题。但我目前无能为力。
尝试沿画布x- &使用4个if语句在正方向和负方向上为对象设置动画效果。 (我是JS的新手)我是为什么即时通讯有问题的动画y轴的负面,也是当我注释掉第四条if语句沿x轴的消极运动是可能的,但不会工作当它活跃时。沿x轴和y轴的html5画布动画
我的猜测是if语句中的条件有问题。但我目前无能为力。
主要缺陷是由于旋转的,该方向上的尺寸必须被使用的,在这种情况下总是为宽度。对于当前的尺寸,这并不明显,如果宽度与您看到结果的高度不同(在下面的示例中,我已经更改了测试的尺寸)。
招数二是卡扣的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>
Very很好,谢谢你的回答:) – Znowman
嗯,听起来很熟悉不知何故:d:HTTP://stackoverflow.c om/questions/32823690/creating-animates –
必须是我的同伴之一;) – Znowman
看起来像这样:D讨论的最终版本(http://jsfiddle.net/tfsh2hyd/3/)是否帮助你所有? –