嘗試沿畫布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/)是否幫助你所有? –