I've been having some trouble drawing an svg onto a canvas with javascript. I would like this to work... HTML
<canvas class="buttonCanvas" id="handCanvas" height="60px" width="60px" />
Javascript
function drawHandCanvas(){
var canvas = document.getElementById('handCanvas');
var ctx = canvas.getContext('2d');
var img= document.createElement('img');
img.src='images/handCursor.svg';
img.width = 60; img.height = 60;
ctx.drawImage(img,0,0);
}
drawHandCanvas();
But it doesn't.
If I add an SVG element I can get this to work. HTML
<canvas class="buttonCanvas" id="handCanvas" height="60px" width="60px" />
<img id="handSVG" src="images/handCursor.svg"/>
Javascript
function drawHandCanvas(){
var canvas = document.getElementById('handCanvas');
var ctx = canvas.getContext('2d');
var img=document.getElementById('handSVG');
img.width = 60; img.height = 60;
setTimeout(function(){
ctx.drawImage(img,0,0);
img.hidden='true';
}, 10);
}
drawHandCanvas();
Note that in this 2nd method of doing it I have to use a setTimeout method to get it to work and add an img element at the end of my down, which I hide after drawing on the canvas. Super hacky! If I just use window.onload instead of setTimeout, it doesn't work. It will hide img, but the drawImage() does nothing, presumably because the canvas isn't ready when the window is already done loading. Any thoughts?
I don't have your svg file, but that being said you have to typically wait till the image is loaded before it will load to canvas. It is like drawing something that isn't there. I think this should work for you.
function drawHandCanvas(){
var canvas = document.getElementById('handCanvas');
var ctx = canvas.getContext('2d');
var img= document.createElement('img');
img.onload = function(){
ctx.drawImage(this,0,0);
}
img.src='images/handCursor.svg';
img.width = 60; img.height = 60;
}
drawHandCanvas();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With