0

I can't seem to find how to access and change fill property on an svg file in canvas. When I go to file and change path fill — it works. But I have no idea how to do it through JS. Please help!

Here is how I load it:

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

  • You can't. You would need to load in the SVG file as AJAX, modify it in JS, and then use it as a new image source for drawing to the canvas. – Niet the Dark Absol Jul 29 '20 at 14:44
  • mb there is a way to load and draw path through code, not from a file? – AzazaMaster Jul 29 '20 at 14:47
  • [Draw SVG path data to a Canvas](https://stackoverflow.com/questions/9458239/draw-path-in-canvas-with-svg-path-data-svg-paths-to-canvas-paths) – DBS Jul 29 '20 at 14:50

1 Answers1

1

In order to change the fill you mau use new Path2D to return a newly instantiated Path2D object. Next you can fill the path.

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>
enxaneta
  • 31,608
  • 5
  • 29
  • 42