简体   繁体   中英

Can you draw SVGs onto a canvas in Safari using drawImage?

According to caniuse.com , using an SVGImageElement as the parameter to a context.drawImage call is supported in every browser except Safari.

However, it seems like many people are using a canvas to draw SVGs in Safari?

For example, this post seems to be drawing images (granted the shadows are slightly messed up).

So, can you draw SVGs on a canvas in Safari?

Is it simply that SVGImageElement is not supported, but a regular Image is, and you can simply set the src on an image to an svg , and then it works fine?

If that is indeed the case, then does it really matter that SVGImageElement is not supported in Safari? You can still draw SVGs onto the canvas regardless by just using a regular Image and setting the src to be an svg asset file?

Do I have that right?

Lastly, Path2D seems to have full browser support, but it is a bit more cumbersome to use. Is there any advantage to using ctx.fill(path2D) as opposed to an Image with an svg as its src ?

Yes it's only SVGImageElement (svg: <image> ) as source for drawImage(source,...) that they don't support. You can very well use an HTMLImageElement (html: <img> ) that does point to an SVG document, even in Safari.

As for Path2D vs drawImage() , the former will allow you to draw your shape as part of the context's path drawing operation, using directly all the context's options like fillStyle , lineWidth , dash-offsets, etc. You can even use it directly with methods like isPointInPath() , or clip() etc.
On the other hand using drawImage() with an SVG document, you get only the pixel data of the original SVG document, it basically becomes a simple raster image. So you are limited to composite operations and filters if you want to edit the image. On a lesser level it also becomes an asynchrnous operation to draw it, since you need to wait for the image has loaded. However it allows you to have much more complex graphics than simple <path> data.

So my personal preference would be to use Path2D where you only need simple path data with great flexibility (for instance stored as JSON) and SVG documents for complex graphics that won't change, but that's just personal tastes, you may verg well be fine with only SVG documents too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM