簡體   English   中英

更改 Canvas 上的 SVG 路徑顏色

[英]Change SVG path color on Canvas

我似乎找不到如何訪問和更改 canvas 中 svg 文件的填充屬性。 當我將 go 歸檔並更改路徑填充時,它可以工作。 但我不知道如何通過 JS 做到這一點。 請幫忙!

這是我加載它的方式:

var ctx = canvas.getContext("2d");
markerImage.img = document.createElement("img");
markerImage.img.src = "marker.svg";
ctx.drawImage(markerImage.img, 100, 100, 100, 100);

// FYI, here is how the svg file looks like:

<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M50 58.3333C54.6023 58.3333 58.3333 54.6024 58.3333 50C58.3333 45.3976 54.6023 41.6667 50 41.6667C45.3976 41.6667 41.6666 45.3976 41.6666 50C41.6666 54.6024 45.3976 58.3333 50 58.3333Z" fill="red"/>
<path d="M50 25C36.1667 25 25 36.1667 25 50C25 63.8333 36.1667 75 50 75C63.8333 75 75 63.8333 75 50C75 36.1667 63.8333 25 50 25ZM50 66.6667C40.7778 66.6667 33.3333 59.2222 33.3333 50C33.3333 40.7778 40.7778 33.3333 50 33.3333C59.2222 33.3333 66.6667 40.7778 66.6667 50C66.6667 59.2222 59.2222 66.6667 50 66.6667Z" fill="black"/>
</svg>```

為了更改填充,您可以使用new Path2D返回一個新實例化的 Path2D object。 接下來,您可以填充路徑。

 let c = document.getElementById("c"); let ctx = c.getContext("2d"); let cw = c.width = 100; let ch = c.height = 100; let path = thePath.getAttribute("d"); let path2 = thePath2.getAttribute("d"); let canvasPath = new Path2D(path); let canvasPath2 = new Path2D(path2); ctx.fillStyle = "gold"; ctx.fill(canvasPath); ctx.fillStyle = "#6ab150"; ctx.fill(canvasPath2);
 <canvas id="c"></canvas> <svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg"> <path id="thePath" d="M50 58.3333C54.6023 58.3333 58.3333 54.6024 58.3333 50C58.3333 45.3976 54.6023 41.6667 50 41.6667C45.3976 41.6667 41.6666 45.3976 41.6666 50C41.6666 54.6024 45.3976 58.3333 50 58.3333Z" fill="red"/> <path id="thePath2" d="M50 25C36.1667 25 25 36.1667 25 50C25 63.8333 36.1667 75 50 75C63.8333 75 75 63.8333 75 50C75 36.1667 63.8333 25 50 25ZM50 66.6667C40.7778 66.6667 33.3333 59.2222 33.3333 50C33.3333 40.7778 40.7778 33.3333 50 33.3333C59.2222 33.3333 66.6667 40.7778 66.6667 50C66.6667 59.2222 59.2222 66.6667 50 66.6667Z" fill="black"/> </svg>

暫無
暫無

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

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