伙计们,我想在画布上画4张图片,但每张图片都是随机的x和y ..这里是我的代码
var imgs = [];
var fruits = ["fruit1.png", "fruit2.png", "fruit3.png", "fruit4.png"];
var monsterReady1 = false;
for (var i = 0; i < fruits.length; i++) {
imgs[i] = new Image();
imgs[i].onload = function() {
monsterReady1 = true;
};
imgs[i].src = fruits[i];
}
var monsterXY1 = function() {
monster1.x = (Math.random() * (canvas.width - 100));
monster1.y = (Math.random() * (canvas.height - 100));
};
var draw = function() {
if (monsterReady1) {
for (var i = 0; i < fruits.length; i++) {
ctx.drawImage(imgs[i], monster1.x, monster1.y);
}
}
}
var main = function() {
draw();
requestAnimationFrame(main);
};
monsterXY1();
但是这段代码给了我相同x和y的所有图像,所以我如何随机地制作它们x和y ??
答案 0 :(得分:0)
尝试:
var imgs = [];
var fruits = ["fruit1.png", "fruit2.png", "fruit3.png", "fruit4.png"];
var monsterReady1 = false;
for (var i = 0; i < fruits.length; i++) {
imgs[i] = new Image();
imgs[i].onload = function() {
monsterReady1 = true;
};
imgs[i].src = fruits[i];
}
var draw = function() {
if (monsterReady1) {
for (var i = 0; i < fruits.length; i++) {
monster1.x = (Math.random() * (canvas.width - 100));
monster1.y = (Math.random() * (canvas.height - 100));
ctx.drawImage(imgs[i], monster1.x, monster1.y);
}
}
}
var main = function() {
draw();
requestAnimationFrame(main);
}
main();
我将monster.x
和monster.y
移到了循环中。
答案 1 :(得分:0)
在尝试绘制图像之前,使用图像预加载器确保所有图像都已加载:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var imageURLs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png");
// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
for(var i=0;i<imgs.length;i++){
var randomX=Math.min(cw-imgs[i].width,Math.random()*cw);
var randomY=Math.min(ch-imgs[i].height,Math.random()*ch);
ctx.drawImage(imgs[i],randomX,randomY);
}
}
&#13;
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;