Abhishek Sharma Abhishek Sharma - 9 months ago 46
Javascript Question

Canvas getImageData and putImageData load image partially

Here is my code. I am uploading a image and using like this :

> var canvas = document.createElement('canvas');
> var context = canvas.getContext('2d');
> context.drawImage(image, 0, 0);

This works fine but if I copy the imagedata like below to another canvas. It loads image partially.

var canvas = document.getElementById('myCanvas');
var context1 = canvas.getContext('2d');
context1.putImageData(context.getImageData(0, 0, image.width, image.height), 0, 0);

I tried same approach by creating two canvas and this code which worked fine but without image.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 300, 300);

var d = document.getElementById("myCanvas1");
var btx = d.getContext('2d');
var imgData = ctx.getImageData(0, 0, 300, 300);
btx.putImageData(imgData, 0, 0);

If i create two canvas it works fine but not like the above where I am using in memory canvas.

My HTML file has this :

<canvas id="myCanvas" width="960" height="960"></canvas>
<canvas id="myCanvas1" width="960" height="960"></canvas>

Answer Source

When you create canvases, you need to set their width manually. Default canvas size is 300x150. From here HTMLCanvasElement. Something like this:

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);