LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   JS Traffic Light Fill Problem (https://www.linuxquestions.org/questions/programming-9/js-traffic-light-fill-problem-4175568233/)

JWarren131 01-29-2016 03:21 AM

JS Traffic Light Fill Problem
 
Hi, I have a problem with some JavaScript, which is changing traffic lights. Here is the code:
Code:

<html>
<head>
<title>JS Traffic Lights</title>
</head>
<body>

<button onclick="changeLights()">Change Lights</button>

<canvas id="myCanvas" width="170" height="320"
style="border:1px solid #d3d3d3;"></canvas>

<script>

var c= document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.rect(10, 10, 150, 300);
ctx.stroke();

var ci1 = document.getElementById("myCanvas");
var ci1tx = ci1.getContext("2d");
ci1tx.beginPath();
ci1tx.arc(86, 70, 40, 0, 2*Math.PI);
ci1tx.fillStyle = "FireBrick";
ci1tx.fill(); // This method learnt from the W3 Schools website
ci1tx.stroke();


var ci2 = document.getElementById("myCanvas");
var ci2tx = ci2.getContext("2d");
ci2tx.beginPath();
ci2tx.arc(86, 160, 40, 0, 2*Math.PI);
ci2tx.fillStyle = "Chocolate";
ci2tx.fill();
ci2tx.stroke();

var ci3 = document.getElementById("myCanvas");
var ci3tx = ci3.getContext("2d");
ci3tx.beginPath();
ci3tx.arc(86, 250, 40, 0, 2*Math.PI);
ci3tx.fillStyle = "MediumSeaGreen";
ci3tx.fill();
ci3tx.stroke();

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

function  changeLights() {
ci1tx.fillStyle = "Red";
ci1tx.fill();
sleep(1000);
ci2tx.fillStyle = "DarkOrange";
ci2tx.fill();
sleep(1000);
ci3tx.fillstyle = "Green";
ci3tx.fill();
ci1tx.fillStyle = "FireBrick";
ci1tx.fill();
ci2tx.fillStyle = "Chocolate";
ci2tx.fill();       
}

</script>

</body>
</html>

When I run the code and press the button, the code only fills the bottom circle (ci3tx) with red...

Can anyone help?

Thanks

Ramurd 01-29-2016 08:23 AM

Took me a while to notice; since I never do javascript :-)

You should see that each of your ciX variables are getElementById("myCanvas"); Each of those gets a 2d context from the same canvas.

There is actually the issue: they're all the same; when you do your initial painting, you first paint circle 1, then 2 and finally the third. So each time they get 'updated' to the last circle painted; which hides this issue.

Since I never do javascript, I may be a bit off and certainly cannot provide a solution... would be cool... I love traffic lights :-) (When they're green for me and red for the rest)

To summarize: I think your 'lights' should become really separate objects.

sundialsvcs 02-05-2016 07:04 AM

Also, since this is quite obviously a homework problem :tisk: you should always ask your instructor first.


All times are GMT -5. The time now is 05:00 AM.