多个图像显示带有动态创建的画布的最后一个图像并分配给图像
Multiple Images displaying last image with dynamically created canvas and assigning to images
function innerAjax(FILE_DIR,imgJPGList){
var imgLength = imgJPGList.length;
$("#imgID").empty();// This is a div
if(imgLength!=0){
img = [];
for(i=0;i< imgLength;i++){
// dir = FILE_DIR+"/"+imgJPGList[i];
var canvasCreator = document.createElement("canvas");
canvasCreator.id = imgJPGList[i].substr(0, imgJPGList[i].indexOf('.'));
console.log("canvas id is---"+canvasCreator.id);
var canvas = $(canvasCreator).get(0);
var ctx = canvas.getContext('2d');
img[i] = new Image();
img[i].onload = function() {
console.log("inside onload function");
ctx.drawImage(img[i],0,0);
}
img[i].src = FILE_DIR+"/"+imgJPGList[i];
canvas.width = img[i].width;
canvas.height = img[i].height;
$("#imgID").append(canvas);
$("#imgID").append($("<br/>"));
}
}
$(canvas).mouseover(function myDown(e)
{
console.log("mouseover-----");
})
}
我在单个页面中有多个图像,我正在尝试创建一个动态画布并为其设置图像高度和宽度,以便我可以对图像进行一些注释。但是我的最后一个图像每次都会显示或什么都不显示。任何帮助是值得赞赏的。
您正在循环中执行异步操作,该循环很少按预期工作。
JavaScript 是单线程的,这意味着在循环完成之前不会调用 onload 处理程序中的代码,因此i
将始终是最后一个图像。
您还应该将设置画布大小移动到处理程序内部,因为未完全加载的图像没有宽度/高度(它仅在您的系统上工作,因为图像在浏览器缓存中)。
若要修复最后一个图像问题,请在处理程序中使用 this
,该处理程序将表示在该点加载的图像:
img[i] = new Image();
...
img[i].onload = function() {
// at the time this gets called, the loop has finished
// these need to be here as image won't have width/height until fully loaded
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0,0); // use this (= actual image loaded)
// append canvas to DOM here etc....
}
img[i].src = FILE_DIR+"/"+imgJPGList[i];
相关文章:
- 循环以检查数组中的最后一个图像
- 使用 jQuery 在最后一个图像之后附加 HTML
- 多个图像显示带有动态创建的画布的最后一个图像并分配给图像
- 使jQuery图像滑块停止在最后一个图像,并添加下一个和上一个按钮
- 最后一个图像已完成淡入
- ajax 返回带有循环的图像长度,检查最后一个循环
- 使用onload加载多个图像以调用函数,并且只有最后一个加载的图像调用该函数
- 为什么我的脚本只将最后一个图像上传到我的 FTP 和数据库
- 最后一个图库图像上的fancybox禁用按钮
- 为什么jQuery代码将最后一个图像替换为第一个
- Fancybox重复第一个和最后一个图像
- 使连续的图像只出现在最后一个消失后,而悬停
- Javascript幻灯片显示最后一个图像5次
- 我怎样才能使一个图像滑块停止在最后一个图像和重放按钮
- 使用javascript将图像更改为其他图像,并从最后一个图像重复到第一个图像
- 数组中的最后一个图像重复两次,为什么?
- 图像加载仅加载最后一个图像
- 从PHP中删除最后一个逗号,该逗号将进入javascript图像预加载脚本
- JQuery滑块:从最后一个图像转换到第一个图像
- Javascript Regex-如何提取图像路径之前的最后一个单词