Reputation: 1168
The drawImage
function is working fine if <canvas>
is defined in HTML.
Please check my JSFiddle
But, When I create the canvas using createElement('canvas')
it does not work.
I have tried to convert the image to canvas in the following ways
Try 1:
$scope.canvas = document.createElement('canvas');
$scope.canvas.width = 500;
$scope.canvas.height =1000;
var ctx = $scope.canvas.getContext('2d');
var img = new Image();
img.onload = function() {
alert("image is loaded");
ctx.drawImage(img, 0, 0);
};
img.src="img/default_subject.png";
In this way the canvas shows only blank screen when tried to display using $scope.canvas.toDataURL()
Try 2:
In this try , I have just moved img.src inside of onload()
function
img.onload = function() {
img.src="img/default_subject.png";
ctx.drawImage(img, 0, 0);
};
This try also not working.
Try 3:
In this try, I changed var img = new Image();
to var img = document.createElement('img')
$scope.canvas = document.createElement('canvas');
$scope.canvas.width = 500;
$scope.canvas.height =1000;
var ctx = $scope.canvas.getContext('2d');
var img = document.createElement('img');
img.onload = function() {
alert("image is loaded");
ctx.drawImage(img, 0, 0);
};
img.src="img/default_subject.png";
But, there is no breakthrough .
Please help me find the solution.
Upvotes: 1
Views: 1803
Reputation: 3335
After creating the canvas element, you need to add the canvas element to the document. I have modified your JSFiddle example to use JavaScript to create the canvas element.
var canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height =1000;
document.getElementById("canvasContainer").appendChild(canvas);
var ctx = canvas.getContext('2d');
var img = document.createElement('img');
img.onload = function() {
alert("image is loaded");
ctx.drawImage(img, 0, 0);
};
img.src="http://www.download-free-wallpaper.com/img88/xpwwiirymrkfcacywpax.jpg";
<div id="canvasContainer"></div>
Upvotes: 2