javascript - onload 在课堂上不起作用
问题描述
这是我的代码(对不起,它很长):
class Vec {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
}
class Enemy {
constructor() {
this.pos = new Vec;
this.vel = new Vec;
this.image = new Image();
this.image.onload = () => {
this.image.width /= 4;
this.image.height /= 4;
}
this.image.src = "https://vignette.wikia.nocookie.net/scribblenauts/images/8/8d/Steel_Spike.png/revision/latest?cb=20130105173440";
this.pos.x = WIDTH;
this.pos.y = HEIGHT - GROUND_Y - this.image.height;
}
}
// setup
const ctx = document.getElementById("canvas").getContext("2d");
const WIDTH = 600;
const HEIGHT = 400;
const GROUND_Y = 50;
let enemies = [];
let lastUpdate = 0;
function update(dt, now) {
// create enemy
if (now - lastUpdate > 2000) {
lastUpdate = now;
enemies.push(new Enemy);
}
for (let i = 0; i < enemies.length; i++) {
// update enemy
enemies[i].vel.x = -300;
enemies[i].pos.x += enemies[i].vel.x * dt;
if (enemies[i].pos.x + enemies[i].image.width < 0)
enemies.splice(i, 1);
}
}
function draw() {
// draw background
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
// draw ground
ctx.fillStyle = "#0f0";
ctx.fillRect(0, HEIGHT - GROUND_Y, WIDTH, GROUND_Y);
// draw enemy
ctx.fillStyle = "#f00";
for (let i = 0; i < enemies.length; i++) {
ctx.drawImage(enemies[i].image, enemies[i].pos.x, enemies[i].pos.y, enemies[i].image.width, enemies[i].image.height);
}
}
// game loop (not important for this question)
const TIMESTEP = 1 / 60;
let accumulator = 0;
let lastRender = 0;
function loop(timestamp) {
accumulator += (timestamp - lastRender) / 1000;
lastRender = timestamp;
while (accumulator >= TIMESTEP) {
update(TIMESTEP, timestamp);
accumulator -= TIMESTEP;
}
draw();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
<!DOCTYPE html>
<html>
<head>
<title>Jump_Over_It</title>
<link href="css/default.css" rel="stylesheet" />
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script src="js/main.js"></script>
</body>
</html>
当我运行这段代码时,尖峰的 y 位置变得混乱(运行代码以了解我的意思)。钉子应该在地面上。
我知道是这样的:
this.image.onload = () => {
this.image.width /= scale;
this.image.height /= scale;
}
部分代码不起作用,但我不明白为什么它不起作用。我在这里想要实现的是使图像尺寸更小。我添加的原因this.image.onload
是因为图像的加载是异步的,所以我必须等到图像加载后才能更改图像的宽度和高度。
我怎样才能使这项工作?
解决方案
推荐阅读
- node.js - 如何解决 mongoddb adbpter 查询构建问题中的 $near 查询?
- node.js - nodejs writeFile 仅适用于管理员权限
- r - R通过将事物组合在一起制作百分比的pi图
- python - 在 EventGhost 中使用 Python
- python - 获取网站部分的 id 或 xpath
- python - 用键盘上的一个字母替换另一个字母的脚本
- c# - 我不知道如何使用 C# 修复 ASP.NET MVC 中的这个 cs0161 错误
- c++ - 确定提交作者是否未初始化
- amazon-web-services - 如何将 CodeDeploy 与 ECS、ALB 和 Auto Scaling 结合使用
- django - 如何在 Django 中使用多个数据库