写一个 一群鱼在水里游的html5
<!DOCTYPE html>
<html>
<head>
<title>一群鱼在水里游</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<pre><code><script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const fishImg = new Image();
fishImg.src = "https://i.imgur.com/7XU6kAa.png";
let fishArray = [];
class Fish {
constructor(x, y, speed, size) {
this.x = x;
this.y = y;
this.speed = speed;
this.size = size;
this.frameX = 0;
this.frameY = 0;
this.spriteWidth = 440;
this.spriteHeight = 440;
}
update() {
this.x -= this.speed;
if (this.x < -100) {
this.x = canvas.width + 100;
this.y = Math.random() * (canvas.height - 200) + 100;
this.speed = Math.random() * 5 + 1;
}
this.frameX = (this.frameX + 1) % 8;
}
draw() {
ctx.drawImage(
fishImg,
this.frameX * this.spriteWidth,
this.frameY * this.spriteHeight,
this.spriteWidth,
this.spriteHeight,
this.x,
this.y,
this.size,
this.size
);
}
}
function init() {
for (let i = 0; i < 20; i++) {
let size = Math.random() * 50 + 50;
let x = Math.random() * canvas.width;
let y = Math.random() * (canvas.height - 200) + 100;
let speed = Math.random() * 5 + 1;
let fish = new Fish(x, y, speed, size);
fishArray.push(fish);
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < fishArray.length; i++) {
fishArray[i].update();
fishArray[i].draw();
}
}
init();
animate();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/0ml 著作权归作者所有。请勿转载和采集!