How to draw svg on top of canvas?

by cortez.connelly , in category: Javascript , 2 months ago

How to draw svg on top of canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 2 months ago

@cortez.connelly 

To draw an SVG on top of a canvas, you can follow these steps:

  1. Create a Canvas element: First, create a Canvas element using HTML.
1
<canvas id="myCanvas" width="200" height="100"></canvas>


  1. Create an SVG element: Next, create an SVG element using HTML and define the SVG graphic that you want to draw.
1
2
3
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="50" height="50" fill="red" />
</svg>


  1. Get the canvas and SVG elements in JavaScript: Use JavaScript to get the canvas and SVG elements by their IDs.
1
2
3
4
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var svg = document.querySelector('svg');


  1. Convert SVG to a data URI: Convert the SVG element to a data URI using XMLSerializer.
1
2
3
4
5
6
var serializer = new XMLSerializer();
var svgString = serializer.serializeToString(svg);

var DOMURL = window.URL || window.webkitURL || window;
var svgBlob = new Blob([svgString], { type: 'image/svg+xml' });
var url = DOMURL.createObjectURL(svgBlob);


  1. Draw the SVG on the canvas: Use the drawImage method of the CanvasRenderingContext2D object to draw the SVG on the canvas.
1
2
3
4
5
6
var img = new Image();
img.onload = function() {
  ctx.drawImage(img, 0, 0);
  DOMURL.revokeObjectURL(url);
}
img.src = url;


  1. Make sure the CORS policy is set correctly if the SVG image is hosted on a different domain.


With these steps, you can draw an SVG on top of a canvas.