canvasArray
包含拆分图像,当在浏览器中打开时,<canvas>
元素应该显示在表格中,例如 3x3
第一次打开页面时,屏幕上会呈现一个空表(问题),再次单击时,它会<canvas>
正确显示元素,大概是因为它们被缓存了
他们为什么没有第一次显示?我尝试ctx.drawImage(img,xoffset,yoffset);
在代码中使用两次,在onload
事件内部和外部
思考是如果图像没有在循环外正确绘制,一旦onload
事件触发它会再试一次,但它不会..
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;
}};