0

Let's say I have the following code which draws a heart:

const ctx = document.querySelector("canvas").getContext("2d");

const pathHeart = new Path2D("M9.293 1.55l.707.708.707-.707a5 5 0 1 1 7.071 7.071l-7.07 7.071a1 1 0 0 1-1.415 0L2.222 8.622a5 5 0 1 1 7.07-7.071z");

ctx.fill(pathHeart);
<canvas></canvas>

Is it possible to draw this at a given position? That is, I am looking for a way to do something like this:

ctx.fill(pathHeart, 100, 100);

To draw this icon at x: 100, y: 100 on the canvas. I cannot simply edit the path data because depending on the state of the application the icon will be drawn at a different location at the canvas.

I believe that I might be able to do something like.. translating the entire canvas, drawing the icon, and then translating it back, but that seems like overkill probably? And potentially not very performant? Is there a better way?

In addition, I cannot simply use context.drawImage because that is not support for SVGs on Safari.

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • hope this can solve your problem https://stackoverflow.com/questions/59631446/how-to-position-path2d-svg-element-in-canvas – xubeiyan Sep 19 '22 at 01:04
  • Does this answer your question? https://stackoverflow.com/a/59631650/1533592 – dale landry Sep 19 '22 at 01:59
  • No better way? Alright, then yeah, it does. – Ryan Peschel Sep 19 '22 at 02:02
  • I added another answer which may fill better some edge cases, but indeed using the context CTM is generally what you'll want. That's not overkill, for the engine the taht you use the CTM or the path definition to offset your drawings makes no sensible difference. – Kaiido Sep 19 '22 at 02:10

0 Answers0