我想从数组在网页上绘制图像,但是网站上没有图像。我想在网站上显示6张图像的阵列,我还想使其向上移动,并且我想在x轴上随机显示它们,但是网站上没有图像
var canvas = document.getElementById('canvas');
var c = canvas.getContext("2d");
var description = [ "cerveny", "fialovy", "cierny", "zeleny", "modry", "zlty"];
var pictures = new Array(5);
function initialize(){
pictures[0] = new Image(50, 50);
pictures[0].src = "cerveny_novy.png";
pictures[1] = new Image(50,50);
pictures[1].src = "fialovy_novy.png";
pictures[2] = new Image(50,50);
pictures[2].src = "cierny.png";
pictures[3] = new Image(50,50);
pictures[3].src = "zeleny_novy.png";
pictures[4] = new Image(50,50);
pictures[4].src = "modry_novy.png";
pictures[5] = new Image(50,50);
pictures[5].src = "novy_zlty.png";
}
initialize();
for (var i = 0; i < 6; i++)
{
c.drawImage(pictures[i], 50, 400, 600, 200);
}
答案 0 :(得分:0)
那是因为您试图使用drawImage()将图像绘制到画布上,而不确保图像已完成加载。 首先创建一个临时变量,该变量将引用您要绘制的图像
var image = new Image();
第二次为其分配一个事件侦听器,该侦听器将监视图像的加载,并会回调一个实际绘制图像的函数。
image.onload = function() {
c.drawImage(image, 100, 100);
}
最后将临时图像的src属性更改为所需图像以开始加载
image.src=images[0].src;
答案 1 :(得分:0)
似乎您没有在绘制图像之前等待图像加载。
尝试绘制onLoad:
pictures[i].onload = function(){
c.drawImage(pictures[i], 50, 50);
};
pictures[i].src = "novy_zlty.png";
您可能想创建一个绘图函数,并在图片数组的每个元素的onload中调用它。
请参见https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
答案 2 :(得分:0)
您忘记绑定onload
处理程序
var c = canvas.getContext("2d");
var description = new Array ("cerveny", "fialovy", "cierny", "zeleny", "modry", "zlty");
var img=[
"https://picsum.photos/id/231/50/50",
"https://picsum.photos/id/232/50/50",
"https://picsum.photos/id/233/50/50",
"https://picsum.photos/id/234/50/50",
"https://picsum.photos/id/235/50/50",
"https://picsum.photos/id/237/50/50",
]
function initialize(){
return img.map(p=>new Image(50, 50)).map((p,i)=>{
p.src = img[i];
p.onload = () => c.drawImage(p, Math.random()*200, 20*i, 50, 50);
return p;
});
}
var pictures= initialize();
<canvas id="canvas" width=250 height=150></canvas>