HTML5 canvas – draw image using svg xml string

HTML5 canvas can be used to draw image from svg xml string using drawImage(). For this the image source should be data:image/svg+xml;charset=utf-8,SVG_STRING. Here is code snippet to show how it works.

<canvas id="canvas1" width="200" height="100" style="background-color:lightgray;"></canvas>
<script type="text/javascript">
window.addEventListener("load", draw);
function draw() {
  var ctx = document.querySelector('#canvas1').getContext('2d');
  var img1 = new Image();
  img1.onload = function() {
    ctx.drawImage(img1, 30, 10);
  img1.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent('<svg xmlns="" width="110" height="60"><rect width="100" height="50" style="fill:green;" /><text x="20" y="20" style="font-size:14px;fill:white;">Hello</text></svg>');

Note that ctx.drawImage() is called on img.onload to ensure image is loaded at the time of drawing image.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments