I have two canvases, shown in the attached image. Each canvas has a width and height of 100 pixels. Assume I have used the canvas method getImageData() to create an image data object:
var c1 = getElementById("canvas1");
var ctx1 = c1.getContext("2D");
var imageData = ctx1.getImageData(0,0,c1.width,c1.height);
I would like to copy the lower left quadrant of canvas1 to the upper right quadrant of canvas2. After reading documentation on the 7-argument version of putImageData() I thought the following would result in "C" appearing in the upper right quadrant of canvas2:
ctx2.putImageData(imageData,50,0,0,50,50,50);
This didn't work. Instead the "C" appeared in the lower right quadrant of canvas2.
I assumed the first two numbers (50,0) specified the x,y coords of the upper left corner of the destination area. I also thought the next two numbers (0,50) specified the upper left corner of the rectangular area inside imageData that is to be copied. The last two numbers (50,50) are the width and height of the rectangular area to be copied.
I hope someone can show me the correct parameters to use.
Thank you.
The meaning of the additional parameters of the putImageData method are indeed a bit confusing.
If you determine 0,50,50,50 for those it does not mean that it just copies the data of the lower half of your 100x100 imageData. In fact, it just masks the upper half (effecively making it invisible) - the data to be drawn is still the whole 100 x 100 area.
If you want the lower-left quadrant copied to the upper-right, you have to shift it up by 50 pixels vertically.
let canvas = document.getElementById("canvas");
let ctx1 = canvas.getContext("2d");
let ctx2 = document.getElementById("canvas2").getContext("2d");
ctx1.font = '16px sans-serif';
ctx1.fillText('A', canvas.width * .25, canvas.height * .25);
ctx1.fillText('B', canvas.width * .75, canvas.height * .25);
ctx1.fillText('C', canvas.width * .25, canvas.height * .75);
ctx1.fillText('D', canvas.width * .75, canvas.height * .75);
let imageData = ctx1.getImageData(0, 0, canvas.width, canvas.height);
ctx2.putImageData(imageData, 50, -50, 0, 50, 50, 50);
canvas {
background: PaleTurquoise;
}
<canvas id="canvas" width="100" height="100"></canvas>
<canvas id="canvas2" width="100" height="100"></canvas>