簡體   English   中英

在 HTML Canvas 中的圖像頂部繪制圓/弧

[英]Drawing a circle / arc on top of an image in HTML Canvas

我有一個簡單的 canvas 作為背景,底部有一個圖像,我正在嘗試繪制一個與圖像重疊的圓圈。 我有點不知道要使用哪個globalCompositeOperation ,以使弧/圓出現在 canvas 的圖像頂部。

代碼:

 var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var centerX = canvas.width / 2; var centerY = canvas.height / 2; var radius = 70; context.fillStyle = "#29BEF1"; context.fillRect(0, 0, 800, 131); var img = new Image; img.src = 'https://i.imgur.com/aN26XpH.png'; img.onload = function() { context.drawImage(img, 0, 29) } context.beginPath(); context.arc(800, -29, 87, 0, 2 * Math.PI); context.closePath(); context.fillStyle = '#FEDB62'; context.fill();
 body { margin: 0px; padding: 0px; }
 <canvas id="myCanvas" width="800" height="131"></canvas>

問題是由於加載圖像是異步的,然后一旦加載並繪制它就會與已經繪制的內容重疊。

一個解決方案是將繪制太陽的代碼移動到onload回調中。

img.onload = function() {
  // draw image
  context.drawImage(img, 0, 29)

  // draw sun
  context.beginPath();
  context.arc(800, -29, 87, 0, 2 * Math.PI);
  context.closePath();
  context.fillStyle = '#FEDB62';
  context.fill();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM