【问题标题】:Change SVG path color on Canvas更改画布上的 SVG 路径颜色
【发布时间】:2020-11-19 04:42:57
【问题描述】:

我似乎无法找到如何访问和更改画布中 svg 文件的填充属性。当我去文件并更改路径填充时-它可以工作。但我不知道如何通过 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>```

【问题讨论】:

  • 你不能。您需要将 SVG 文件作为 AJAX 加载,在 JS 中对其进行修改,然后将其用作新的图像源以绘制到画布上。
  • mb 有没有办法通过代码而不是文件来加载和绘制路径?

标签: javascript svg canvas


【解决方案1】:

为了更改填充,您可以使用new Path2D 返回一个新实例化的 Path2D 对象。接下来就可以填充路径了。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2022-08-02
    • 2016-07-29
    • 2013-12-19
    • 2014-11-18
    • 1970-01-01
    • 2021-01-12
    相关资源
    最近更新 更多