html 5 中的圆圈未出现在图像上

Circle not appearing over image in html 5

我正在尝试在图像上添加一个圆圈,我也在使用 .onload 函数,但圆圈仍在图像下方绘制。

<!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>

当我 运行 代码片段时,在呈现图像之前有一小段时间可以看到圆圈。图像在渲染之前必须等待加载,但立即绘制圆圈。因此,先绘制圆圈,然后将图像放在圆圈之上。要解决此问题,您可以在渲染图像后绘制圆圈。请参阅此修改后的代码片段:

<!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>