HTML5場景代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HTML5場景代碼</title> <style> body{ margin: 0; padding: 0; overflow: hidden; } canvas{ width: 100%; height: 100%; } </style> </head> <body> <canvas id="myCanvas"></canvas> <script> const canvas = document.querySelector("#myCanvas"); const ctx = canvas.getContext("2d"); let frames = 0; //定義矩形類 class Rect{ constructor(x, y, width, height, color){ this.x = x; this.y = y; this.width = width; this.height = height; this.color = color; } //畫矩形 draw(){ ctx.fillStyle = this.color; ctx.fillRect(this.x, this.y, this.width, this.height); } } //定義動畫函數 function animate(){ frames++; ctx.clearRect(0, 0, canvas.width, canvas.height); //隨機生成顏色 const red = Math.floor(Math.random()*256); const green = Math.floor(Math.random()*256); const blue = Math.floor(Math.random()*256); const color = `rgb(${red},${green},${blue})`; //生成400個隨機矩形 for(let i = 0;i<400;i++){ const x = Math.floor(Math.random()*canvas.width); const y = Math.floor(Math.random()*canvas.height); const width = Math.floor(Math.random()*50+20); const height = Math.floor(Math.random()*50+20); const rect = new Rect(x, y, width, height, color); rect.draw(); } //動畫循環 requestAnimationFrame(animate); } //啟動動畫 animate(); </script> </body> </html>