生成随机图像在画布在javascript

spawn random images in canvas in javascript

本文关键字:javascript 图像 随机      更新时间:2023-09-26

大家好,我正在尝试使用画布制作javascript游戏。我想随机生成敌人对象。到目前为止,我发现这是一个产卵的例子:JSFiddle Demo

如何加载图像而不是球?任何帮助都太好了。Tnx .

// get a refrence to the canvas and its context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// newly spawned objects start at Y=25
var spawnLineY = 25;
// spawn a new object every 1500ms
var spawnRate = 1500;
// set how fast the objects will fall
var spawnRateOfDescent = 0.50;
// when was the last object spawned
var lastSpawn = -1;
// this array holds all spawned object
var objects = [];
// save the starting time (used to calc elapsed time)
var startTime = Date.now();
// start animating
animate();

function spawnRandomObject() {
// select a random type for this new object
var t;
// About Math.random()
// Math.random() generates a semi-random number
// between 0-1. So to randomly decide if the next object
// will be A or B, we say if the random# is 0-.49 we
// create A and if the random# is .50-1.00 we create B
if (Math.random() < 0.50) {
    t = "red";
} else {
    t = "blue";
}
// create the new object
var object = {
    // set this objects type
    type: t,
    // set x randomly but at least 15px off the canvas edges
    x: Math.random() * (canvas.width - 30) + 15,
    // set y to start on the line where objects are spawned
    y: spawnLineY,
}
// add the new object to the objects[] array
objects.push(object);
}

function animate() {
// get the elapsed time
var time = Date.now();
// see if its time to spawn a new object
if (time > (lastSpawn + spawnRate)) {
    lastSpawn = time;
    spawnRandomObject();
}
// request another animation frame
requestAnimationFrame(animate);
// clear the canvas so all objects can be 
// redrawn in new positions
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw the line where new objects are spawned
ctx.beginPath();
ctx.moveTo(0, spawnLineY);
ctx.lineTo(canvas.width, spawnLineY);
ctx.stroke();
// move each object down the canvas
for (var i = 0; i < objects.length; i++) {
    var object = objects[i];
    object.y += spawnRateOfDescent;
    ctx.beginPath();
    ctx.arc(object.x, object.y, 8, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fillStyle = object.type;
    ctx.fill();
}
}

Here

一种方法是使用全局数组来加载图像:

var images = [img1, img2, ... ];

当一个对象被创建时,它被随机分配给images数组中的一个图像。然后我们可以用ctx.drawImage法绘制它的图像:ctx.drawImage(object.image,...))。现在重要的是要记住,你需要首先加载所有的图像,像这样:

var img1 = new Image();
img.src = "...";

并且仅在加载所有内容时运行animate,我们可以使用onload:

window.onload = function() {
    animate();
}

这是对象。image属性添加到object的创建中。这是从我们的images数组中选择一个随机图像。

var object = {
    ...
    // give random image
    image: images[Math.floor(Math.random()*images.length)]
}

最后我们可以删除arc的绘制函数和绘制,并使用object.image绘制:

for (var i = 0; i < objects.length; i++) {
    var object = objects[i];
    object.y += spawnRateOfDescent;
    ctx.drawImage(object.image, object.x, object.y, 30, 30);
}