I want to show four canvas from the same image
I'm working with an image which I need to be splitted into four pieces. I don't know the actual dimensions of the image so I need it to be dynamic. I already get this far, and I think the first piece is working fine, but I don't know why it is not working for the rest of the pieces. Could you point where the error could be?
I am new working with canvas, so my code is based on this answer: https://stackoverflow.com/a/8913024/6929416
var image = new Image();
image.crossOrigin = 'anonymous';
image.src = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png';
image.onload = cutImageUp;
function cutImageUp() {
var natW = image.width / 2;
var natH = image.height / 2;
var widthOfOnePiece = jQuery(window).width() / 2;
var heightOfOnePiece = jQuery(window).height() / 2;
var imagePieces = [];
for (var x = 0; x < 2; ++x) {
for (var y = 0; y < 2; ++y) {
var canvas = document.createElement('canvas');
canvas.width = widthOfOnePiece;
canvas.height = heightOfOnePiece;
var context = canvas.getContext('2d');
context.drawImage(image,
x * natW, y * natH,
natW, natH,
x * canvas.width, y * canvas.height,
canvas.width, canvas.height
);
/*drawImage(image,
sx, sy,
sWidth, sHeight,
dx, dy,
dWidth, dHeight);*/
imagePieces.push(canvas.toDataURL());
}
}
// imagePieces now contains data urls of all the pieces of the image
// load one piece onto the page
var anImageElement = document.getElementById('testing');
var anImageElement2 = document.getElementById('testing2');
var anImageElement3 = document.getElementById('testing3');
var anImageElement4 = document.getElementById('testing4');
anImageElement.src = imagePieces[0];
anImageElement2.src = imagePieces[1];
anImageElement3.src = imagePieces[2];
anImageElement4.src = imagePieces[3];
}
img{ border: 1px solid; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<img id="testing" src="">
<img id="testing2" src="">
<img id="testing3" src="">
<img id="testing4" src="">
</section>
I expect the canvas dimensions to fit on the screen, so I set them to half of the windows width and height.