Franco Gargiulo Franco Gargiulo -3 years ago 108
HTML Question

Change color of a drawing in canvas after loop ends

I'm working on an assignment I got and I can't find a solution.
It's a js canvas drawing of a ball that goes from left to right and once it reaches a specific x-coordinates starts again from the left, over and over.
I want to make it go from yellow to blue alternatively once it starts its cycle again. This is my code:

/* --- HTML --- */

<!DOCTYPE html>
<html>
<head>

<title>CANVAS</title>
<script src="main.js"></script>
</head>
<body id="contenido">

<section id="tres">
<p>3</p>
<canvas id="lienzoTres" width="500" height="300"></canvas>
</section>

</body>
</html>

/* --- JS --- */

function animar() {
var elemento=document.getElementById('lienzoTres');
lienzo3=elemento.getContext('2d');
x=70;
y=130;
radio=70;
lienzo3.fillStyle="yellow";
intervalo=setInterval(circuloAmarillo, 5);
}
window.addEventListener("load", animar, false);

function circuloAmarillo(){
lienzo3.clearRect(x - radio, y - radio, radio * 2, radio * 2);
x++;
lienzo3.beginPath();
lienzo3.arc(x,y,radio,0,Math.PI*2, false);
lienzo3.fill();
if(x>=430){
lienzo3.clearRect(0, 0, 550, 300);
x=70;
cambiacolor();
}
}

function cambiacolor() {
if (lienzo3.fillStyle=="yellow") {
lienzo3.fillStyle="blue";
} else if (lienzo3.fillStyle=="blue") {
lienzo3.fillStyle="yellow";
}
}


I dind't include css because it doesn't seem to be the problem.
Any thoughts on how I can make it switch from yellow to blue every time it completes a left-to-right run?

Thanks!

Answer Source

As Anami has pointed out, you have to change your cambiacolor method as below

function cambiacolor() {
  if (lienzo3.fillStyle == "#ffff00") {
    lienzo3.fillStyle = "blue";
  } else if (lienzo3.fillStyle == "#0000ff") {
    lienzo3.fillStyle = "yellow";
  }
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download