'RequestanimationFrame wont activate, vanilla js
I want a second animation to activate when the first animation x and y coordinates reach a certain point in a canvas.
Some variables:
var canvas=document.querySelector("#mittCanvas");
var ctx=canvas.getContext("2d");
var animasjonID;
var kanonID;
var aktiv=false;
Function that runs the first animation.
animasjonID = requestAnimationFrame(animer);
var array = [];
for (var i = 0; i < 6; i++) {
setTimeout(loop, i * 3000);
}
function loop(){
array.push(new fiende(0,450,10,"blue"));
}
function animer() {
if (array.length === 0) {
cancelAnimationFrame(animasjonID);
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < array.length; i++) {
array[i].flytt();
if (array.length === 0) {
break
}
array[i].tegn();
}
}
class fiende {
constructor(x, y, radius, farge) {
this.x = x;
this.y = y;
this.radius = radius;
this.farge = farge;
}
tegn() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 5;
ctx.stroke();
ctx.fillStyle = this.farge;
ctx.fill();
ctx.closePath();
}
flytt() {
if (this.x > 300) {
if (this.y < 360) {
if (this.y < 210) {
if (this.y < 55) {
if (this.y < 10) {
array.shift();
} else {
this.y -= 0.3;
}
} else {
this.x += 0.4;
this.y -= 0.31;
}
} else {
this.x -= 0.2;
this.y -= 0.33;
}
} else {
this.x += 0.4;
this.y -= 0.3;
}
} else {
this.x += 0.5;
}
if (avstandtaarn1(array[0]) < 200) {
if (aktiv === true) {} else {
//Here is the problem, when the distance is less than 200, it wont start the second
//animation
kanonID = requestAnimationFrame(Kanimer);
aktiv = true;
}
}
}
}
Why wont the it trigger the second kanonIDanimation?
Function to calculate distance:
function avstandtaarn1(obj1){
var xAvstand2=Math.pow(obj1.x-275,2);
var yAvstand2=Math.pow(obj1.y-330,2);
var avstand=Math.sqrt(xAvstand2+yAvstand2);
return avstand;
}
Second animation, very similar to first
function Kanimer() {
kanon.kflytt();
kanon.ktegn();
kanonID = requestAnimationFrame(Kanimer);
}
class kanonkule {
constructor(kx, ky) {
this.kx = kx;
this.ky = ky;
}
kflytt() {
this.kx += 1;
this.ky += 1;
}
ktegn() {
ctx.beginPath();
ctx.arc(this.kx, this.ky, 5, 0, Math.PI * 2);
ctx.strokeStyle = "#000000";
ctx.lineWidth = 5;
ctx.stroke();
ctx.fillStyle = "black";
ctx.fill();
ctx.closePath();
}
}
var kanon = new kanonkule(275, 330);
Now if i add this line outside of any loops and function
kanonID=requestAnimationFrame(Kanimer);
Then the second animation starts immediately, so im certain the problem must be where i highlighted.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
