嘿,我真的希望有人帮助我。 所以,基本上我只是尝试我的画布技巧。我想制作一个射击游戏,我在一堆表情符号上拍摄不同的y轴点,不同的高度,并在x轴上以不同的速度滑动。
我有一些emogi图像,我将它们重命名为enumrable。我努力的地方是在弧内显示图像。此外,我希望整个图像以10 x 10 /等显示,而不仅仅是溢出它。
我真的希望有人帮助我,谢谢。
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var height = canvas.height = window.innerHeight;
var width = canvas.width = window.innerWidth;
function random(min, max) {
var num = Math.floor(Math.random() * (max - min)) + min;
if (num === 0) {
return 2;
}
return num;
}
function Target(x, y, velX, radius, image) {
this.x = x;
this.y = y;
this.velX = velX;
//this.velY = velY;
this.radius = radius;
this.image = image;
}
Target.prototype.update = function () {
if (this.x + this.radius >= width) {
this.velX = -this.velX;
}
if (this.x + this.radius <= width) {
this.velX = -this.velX;
}
/*if (this.y + this.radius >= height) {
this.velY = -this.velY;
}
if (this.y + this.radius >= 0) {
this.velY = -this.velY;
}*/
this.x += this.velX;
//this.y += this.velY;
};
Target.prototype.draw = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, true);
ctx.fillStyle = ctx.createPattern(this.image, 'no-repeat');
ctx.fill();
this.update();
};
//var target1 = new Target(30, 40, 20, 20);
function loop() {
ctx.fillRect(0, 0, width, height);
var targets = [];
var img = new Image();
while (targets.length < 25) {
img.src = './images/emogi' + random(1, 6) + '.jpg';
img.repeat = 'no-repeat';
img.maxHeight = 10;
img.maxWidth = 10;
var target = new Target(
random(100, 500),
random(100, 500),
random(10, 30),
20,
img
);
targets.push(target);
}
for (var i =0; i< targets.length; i++) {
target[i].draw();
target[i].update();
}
requestAnimationFrame(loop);
}
loop();
答案 0 :(得分:0)
您的问题是您没有看到图像。发生这种情况是因为您开始加载图像然后立即绘制它。画画时,没有图像。它尚未加载!
要修复它,您必须预加载所有图像
示例
Let images = {
“emoji”: {}
};
function loadImages() {
return new Promise((resolve, reject) => {
// initiate loading
// wait for all to load
// resolve promise
});
}
loadImages.then(startGame);
您可能会发现这个问题很有帮助 Javascript/HTML5 using image to fill canvas