canvasArray contains the split image, when opened in browser the <canvas> elements are supposed to be displayed in a table e.g 3×3
First time opening page an emtpy table is rendered on screen (issue), when clicked again it displayed the <canvas> elements correctly, presumably because they are cached
How come they are not displaying first time? I tried using ctx.drawImage(img,xoffset,yoffset); twice in the code, inside the onload event and outside
Thinking being if image doesnt draw correctly outside the loop, once onload event fires it will try again, but it does not ..
Image URL<input type="text" id="image" value="images/hippo.jpg"/><br>
var canvasArray = Project.split( $("#image").val() , rowCount * rowCount);
// eg Project.split("https://image.com/funny.jpg, 3, 3");
var Project = {
split: function(imgsrc, tiles) {
var img = new Image(),
canvasArray = new Array(),
imgWidth,
imgHeight,
r,g,b = 0;
img.onload = function(){
xoffset = 0,
offset = 0;
for (var i = 0; i < tiles; i++){
//create canvas element and set attributes and get the canvas context
canvasArray[i] = document.createElement('canvas');
canvasArray[i].setAttribute('width', tileW);
canvasArray[i].setAttribute('height', tileH);
canvasArray[i].setAttribute('id', 'canvas'+i);
var ctx = canvasArray[i].getContext('2d');
ctx.drawImage(img,xoffset,yoffset);
//if i is a multiple of the total number of tiles to a row,
//move down a column and reset the row_col
if((i + 1) % row_col == 0){
yoffset -= tileH;
xoffset =0;
}else{
//otherwise move across the image
xoffset -= tileW;
}
}
};
img.src = imgsrc;
//get the number of tiles in a row or column (row == column )
var row_col = Math.sqrt(tiles),
tileH = img.height / row_col,
tileW = img.width / row_col,
canvasArray = [tiles];
var xoffset = 0,
yoffset = 0;
for (var i = 0; i < tiles; i++){
//create canvas element and set attributes and get the canvas context
canvasArray[i] = document.createElement('canvas');
canvasArray[i].setAttribute('width', tileW);
canvasArray[i].setAttribute('height', tileH);
canvasArray[i].setAttribute('id', 'canvas'+i);
var ctx = canvasArray[i].getContext('2d');
ctx.drawImage(img,xoffset,yoffset);
//if i is a multiple of the total number of tiles to a row,
//move down a column and reset the row_col
if((i + 1) % row_col == 0){
yoffset -= tileH;
xoffset =0;
}else{
//otherwise move across the image
xoffset -= tileW;
}
}
return canvasArray;
}};
You need to check
completeof img, select image itself instead ofval, calculate image dimensions inside onload handler, also as image loading is asynchronous operation, you need use callback, instead of return array:DEMO