How to draw SVG image on canvas with Konva

How to show SVG image on canvas?

It has not always been possible for browsers to draw *.svg images onto the canvas. However, the situation has improved and you currently have several options available if you want to render a vector image with Konva:

Option 1: Use Konva.Image

In most of the cases you can use *.svg image the same way as any other image such as *.png or *.jpg. You can use Konva.Image shape.

Konva.Image.fromURL('/image.svg', (image) => {
layer.add(image);
});

This method works well in many cases, but is not fully cross-compatible. For example, some SVG may not be visible in the Firefox browser (there is a workaround for that case).

Option 2: Use Konva.Path

Use Konva.Path. This method is good for simple path shapes. If you have a large SVG with many paths you, you may need to split it manually into several Konva.Path shapes.

Option 3: Use an external library to render SVG to canvas

Use an external library (for example, canvg) to draw the SVG into the <canvas> element. And then use that canvas for Konva.Image.

This method has been tested in at least one large production app, with proven reliability and rendering accuracy.

Demo

Below is a demo that shows drawing natively and with a library.

Konva GIF demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/canvg/dist/browser/canvg.min.js"></script>
<meta charset="utf-8" />
<title>Konva SVG Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>

<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});

var layer = new Konva.Layer();
stage.add(layer);

var SOURCE = '/assets/tiger.svg';
// try to draw SVG natively
Konva.Image.fromURL(SOURCE, (imageNode) => {
layer.add(imageNode);
imageNode.setAttrs({
width: 150,
height: 150,
});
});

// draw svg with external library
var canvas = document.createElement('canvas');
canvg(canvas, SOURCE, {
renderCallback: function () {
var image = new Konva.Image({
image: canvas,
x: 200,
width: 150,
height: 150,
});
layer.add(image);
},
});
</script>
</body>
</html>
Enjoying Konva? Please consider to support the project.