Haruke Sensei
Haruke Sensei

Reputation: 57

Circle not appearing over image in html 5

I am trying to add a circle over the image and I am using the .onload function too but the circle is still being drawn below the image.

<!DOCTYPE html>
<html>
<body>
  <canvas id="myCanvas" width="1024" height="500" style="border:1px solid #d3d3d3;">
    Your browser does not support the canvas element.
  </canvas>

  <script>
    var canvas = document.getElementById("myCanvas");
    var background = new Image();
background.src = "https://i.imgur.com/ua7gL3M.png";

// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
    ctx.drawImage(background,0,0);   
}
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(512,200,60,0,2*Math.PI);
ctx.strokeStyle = "red"
ctx.lineWidth = 5;
ctx.stroke();
  </script>

</body>

</html>

Upvotes: 0

Views: 54

Answers (1)

Kenny
Kenny

Reputation: 61

When I run the code snippet, there's a brief moment the circle is visible before the image is rendered. The image has to wait to load before it is rendered, but the circle is being drawn immediately. Because of that, the circle is drawn first then the image is placed on top of it. To fix this, you can draw the circle after the image is rendered. See this revised code snippet:

<!DOCTYPE html>
<html>
<body>
  <canvas id="myCanvas" width="1024" height="500" style="border:1px solid #d3d3d3;">
    Your browser does not support the canvas element.
  </canvas>

  <script>
    var canvas = document.getElementById("myCanvas");
    var background = new Image();
    background.src = "https://i.imgur.com/ua7gL3M.png";

    // Make sure the image is loaded first otherwise nothing will draw.
    background.onload = function(){
        ctx.drawImage(background,0,0); 

        // The following lines were moved into the onload callback
        ctx.beginPath();
        ctx.arc(512,200,60,0,2*Math.PI);
        ctx.strokeStyle = "red"
        ctx.lineWidth = 5;
        ctx.stroke();  
    }
    var ctx = canvas.getContext("2d");
  </script>

</body>

</html>

Upvotes: 1

Related Questions