图像数组不能绘制到画布上
Image array won't draw to canvas
我正在学习JavaScript。如果有人能解释一下我在哪里做错了就太好了。
我有一个包含图片链接的数组,并将它们放入函数中,该函数应该为每个带有链接的图片在画布中绘制图像。
function draw(imgs){
var step = 0; // I want to start with zero;
imgs.forEach(function(src){ // then go through the array links
// and I want to draw the images from the array
con.drawImage(src, 0, step, 200 , 150)
step += 20; // This is the step for the next picture
console.log(step)
console.log(src)
})
console.log(imgs);
}
然后执行:
window.onload = function(){
setInterval(function(){
loadImg(arr, draw)
}, 1000)
...
显示的是数组的第一张图setInterval
之后是最后一张图
不好意思,现在是凌晨5点
公立小学loadImage是一个函数,用于创建一个包含少量图像src的数组:
function loadImg(linkArr, draw){
var imgs = [];
linkArr.forEach(function(link){
var img = new Image();
img.src = link
imgs.push(img);
})
draw(imgs)
};
很难说你到底在哪里犯了错。似乎所有的图像都是在第一次调用loadmg时同时添加的。为了让您的示例以延迟方式绘制图像,您需要在将实际源添加到数组时设置延迟,因此每个间隔只发送1个URL。
因为这是一个供你学习的例子,所以我就不讨论如何优化它了。
请参阅下面的代码,这是您想要完成的工作示例。看看评论,希望你能明白发生了什么。
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
c.width = 400;
c.height = 400;
var images = [];
var links = ["http://pattersonrivervet.com.au/sites/default/files/pictures/Puppy-10-icon.png",
"https://38.media.tumblr.com/avatar_2be52b9ba912_128.png"];
var counter = 0;
function draw(imgs){
ctx.clearRect(0,0,c.width,c.height);
var step = 0; // I want to start with zero;
imgs.forEach(function(src){ // then go through the array links
// and I want to draw the images from the array
ctx.drawImage(src, 0, step);
step += src.height; // This is the step for the next picture. Let's use the height of the image.
})
}
function loadImg(link){
var img = new Image();
img.src = link;
images.push(img);
draw(images);
};
var myInterval = setInterval(function(){ //I set the interval to a variable so that I can remove it later if needed.
// you can add images in different ways, I used an array of links
loadImg(links[counter]);
counter++; //set counter to next image
if (counter > links.length) {
//if we're out of images, stop trying to add more
clearInterval(myInterval);
}
}, 3000);
ctx.fillText("pictures appear in 3s intervals",10,10);
<canvas id="canvas"></canvas>
相关文章:
- 将ajax数组缓冲区响应绘制到画布中
- HTML5 Canvas - 使用命令数组通过上下文进行绘制
- 如何在浏览器窗口底部的直线上绘制圆圈数组
- 如何在谷歌地图API中使用坐标数组绘制多边形
- d3.js如何从数组中绘制堆叠的水平条
- 从带有循环的数组中一个接一个地在画布上绘制形状
- 使用javascript绘制多个以数组元素为文本中心的圆
- 从数组绘制级别后的冲突检测
- 加载带有 onload 的图像数组,如何限制将它们绘制到画布
- 从谷歌地图中的数组绘制形状
- 从对象数组数组绘制 D3 图表
- 绘制 C3 图表时的 JSON 到数组问题
- 是什么导致我的绘制数组调用无效操作
- 获取与数组匹配的用户输入以绘制到画布上
- 将数据复制到 JavaScript D3 中的数组.js然后绘制散点图
- 从数组中绘制纬度,在谷歌地图中做长
- 谷歌地图API - 在数组中使用Lat Lng坐标绘制折线飞行路径
- 使用 jquery flot 绘制 json 数组
- 使用数据表(Meteor Tabular)在新行中绘制数组的每个元素
- 在画布中绘制数组图像