I recently discovered 3 really exciting SVG
I can't wait to tell you about them!
So I created Faviator
Faviator
However, there are two main issues this library:
@import()
or url()
are not always being loaded when the screenshot is takenDon't get me wrong. convert-svg
is still an amazing project!
The second issue is very crucial for Faviator
So I decided to create my own: @ycm.jason/svg-to-img
As I mentioned, one way to convert SVG
Another approach is with HTML5 canvas<img>
on a canvas
Okay.. So what?
This mean, we can:
<img>
to a SVG<img>
on a <canvas>
<canvas>
as a PNG or JPEGHere is a quick demo:
const img = document.createElement('img');
img.src = 'some/path/to/the/awesome.svg';
img.onload = () => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
// draw img to (0, 0) on the canvas
context.drawImage(img, 0, 0);
// export the PNG or JPEG
const pngDataURL = canvas.toDataURL('image/png');
const jpegDataURL = canvas.toDataURL('image/jpeg');
// ... do something with them ...
};
Notice all this happens in the browser, which enable @ycm.jason/svg-to-img
HiDPI Canvas is a technique introduced by Paul Lewis. It addresses the problem with the High DPI devices and the drawing of canvas
Summary:
Quick example (intended to draw 200x500):
<canvas width="400" height="1000" style="width: 200; height: 500">
</canvas>
This technique enable me to convert SVG
You can see how different they are:
Original SVG
https://svgshare.com/i/7Sp.svg
(the image showing is not an SVG... The image host convert it to png...)
Without HiDPI technique
With HiDPI technique
Can you see the difference? If you focus on tips of the "F", you will notice how the last one matches the original SVG more.
Although this definitely improves the image detail, it still appears to bit a little bit blurry. This could be caused by the resizing of the image. I am not an expert in image processing, would be nice if you can tell me some useful techniques that I could use here.
CSS could be embedded in SVG to control the styles. With the introduction of CSS3 @import
However, if you are displaying your SVG in <img>
, you might find out that the styles are not imported. The browser (or just Chrome) seems to ignore any external resources if SVG is used in <img>
.
I invented a technique called Prefetching SVG which can solve the above problem and make your SVG looks the same even when you are offline!
The idea is to replace @importurl()
with a data url. I have created a library to do this: prefetch-svg
Without prefetching
Since you might have the font-family installed locally, I explicitly removed the
@import
to demonstrate.
With prefetching
And that's it. Here is my little sharing about SVGs. Tell me what you think! Have I missed anything?