EN
JavaScript - draw svg on canvas element
0
points
In this article, we would like to show you how to draw SVG image on an HTML canvas element using JavaScript.
Quick solution:
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
var image = new Image();
image.onload = function() {
// drawImage(image, xStart, yStart, imageWidth, imageHeight)
context.drawImage(image, 50, 50, 100, 100);
};
image.src = 'https://dirask.com/static/bucket/1632934722_loupe.svg';
Practical example
In this example, we create a new Image
with src
set to the path to our svg graphics. Then using drawImage()
method we draw the svg on the canvas.
Note:
Add
drawImage()
method toonload
event to make sure that the graphic will load correctly.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="200" height="200"></canvas>
<script>
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
var image = new Image();
image.onload = function() {
context.drawImage(image, 50, 50, 100, 100); // drawImage(image, x-start, y-start, width, height)
};
image.onerror = function() {
context.fillStyle = 'red';
context.font = '16px Arial';
context.fillText('Image loading error!', 10, 30);
};
image.src = 'https://dirask.com/static/bucket/1632934722_loupe.svg';
</script>
</body>
</html>