Reputation: 25
What i want to do is to draw an image that I have saved locally onto a canvas. I then want to convert that canvas to a png image. The image loads on the canvas but the png image that I create is blank. Does anyone know how to fix this?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="" id="canvasImage" />
<canvas id="canvasId" width="160" height="145"></canvas>
<script>
var canvas = document.getElementById('canvasId');
var context = canvas.getContext("2d");
image = new Image();
image.src = "images/rightarrow.png";
image.onload = function(){
context.drawImage(image, 0, 0);
}
var imgTag = canvas.toDataURL("image/png");
document.getElementById("canvasImage").src = imgTag;
</script>
</body>
</html>
Upvotes: 1
Views: 6758
Reputation: 12324
You need to create your image inside onload
handler
image = new Image();
image.src = "images/rightarrow.png";
image.onload = function(){
context.drawImage(image, 0, 0);
var imgTag = canvas.toDataURL("image/png");
document.getElementById("canvasImage").src = imgTag;
}
Upvotes: 1