三行代码  ›  专栏  ›  技术社区  ›  Haruke Sensei

在HTML5中,圆圈不出现在图像上方

  •  0
  • Haruke Sensei  · 技术社区  · 1 周前

    我试图在图像上添加一个圆圈,我正在使用 .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>
    1 回复  |  直到 1 周前
        1
  •  1
  •   Kenny    1 周前

    当我运行代码片段时,在渲染图像之前,有一个短暂的时刻圆圈是可见的。图像在渲染之前必须等待加载,但圆将立即绘制。因此,首先绘制圆,然后将图像放置在圆的顶部。要解决此问题,可以在渲染图像后绘制圆。请参阅此修订的代码段:

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