【问题标题】:Circle not appearing over image in html 5圆圈没有出现在html 5中的图像上
【发布时间】:2022-01-15 04:19:50
【问题描述】:

我正在尝试在图像上添加一个圆圈,并且我也在使用 .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>

【问题讨论】:

  • 图片加载时间可能比代码执行时间要长,如果在onload里面加了圈代码呢?

标签: javascript html html5-canvas


【解决方案1】:

当我运行代码 sn-p 时,在渲染图像之前有一小段时间圆圈是可见的。图像在渲染之前必须等待加载,但会立即绘制圆圈。因此,首先绘制圆圈,然后将图像放置在其顶部。要解决此问题,您可以在渲染图像后绘制圆圈。看这个修改后的代码sn -p:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    相关资源
    最近更新 更多