charlie elliott
charlie elliott

Reputation: 11

HTML Canvas does not refresh (2)

I was told to ask a more specific question etc....


<!DOCTYPE html>
<html>
<body>

<canvas id="RoomCanvas" width="300" height="200">
<!-- ************************************* -->
<!-- The wall is always here               -->
<!-- ************************************* --> 
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("RoomCanvas");
var ctx = c.getContext("2d");

ctx.clearRect(0, 0, 300, 200);

alert("clear");



doWall("blue", 0);

x = 0;
for (let i = 0; i < 10000; i++) {
  x = x + i;
}

alert("left there");

doWall("pink", 47);


function doWall(theColor, xlocation){
  ctx.beginPath();
     ctx.moveTo(xlocation, xlocation);
     ctx.lineTo(xlocation, 100);
  ctx.closePath();
  ctx.lineWidth = 8;
  ctx.strokeStyle = theColor;
  ctx.stroke();
}

</script>

</body>
</html>

The Problems: 1 - clear rectangle does not work until the program stops running! 2 - the blue line does not appear until the program stops running! 3 - the pink line does not appear until the program stops running!

My application needs to put the blue line out when the program is doing something. When the program finishes what it is doing the pink line is to be displayed along with the blue line.

What good is a canvas that does not show anything until all the drawing is done?

I hope this better describes the problem. Any help will be greatly appreciated.

Charlie

Upvotes: 0

Views: 103

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17674

Here is an example using timeouts

  • The blue line will draw after 500 milliseconds
  • The pink line will draw after 2000 milliseconds

var c = document.getElementById("RoomCanvas");
var ctx = c.getContext("2d");

setTimeout(() => { doWall("blue", 10) }, 500);
setTimeout(() => { doWall("pink", 47) }, 2000);

function doWall(theColor, xlocation) {
  ctx.beginPath();
  ctx.moveTo(xlocation, xlocation);
  ctx.lineTo(xlocation, 100);
  ctx.closePath();
  ctx.lineWidth = 8;
  ctx.strokeStyle = theColor;
  ctx.stroke();
}
<canvas id="RoomCanvas" width="100" height="100"></canvas>


Here is another example using click events:

var c = document.getElementById("RoomCanvas");
var ctx = c.getContext("2d");

function doWall(theColor, xlocation) {
  ctx.beginPath();
  ctx.clearRect(0, 0, c.width, c.height)
  ctx.moveTo(xlocation, xlocation);
  ctx.lineTo(xlocation, 100);
  ctx.closePath();
  ctx.lineWidth = 8;
  ctx.strokeStyle = theColor;
  ctx.stroke();
}
<button onclick="doWall('red', 10)">red</button>
<button onclick="doWall('blue', 20)">blue</button>
<button onclick="doWall('pink', 30)">pink</button>
<button onclick="doWall('black', 40)">black</button>

<br>
<canvas id="RoomCanvas" width="100" height="100"></canvas>

Upvotes: 1

Related Questions