突发奇想写了一写
效果图 点击查看效果
第一步创建html结构
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<canvas id="canvas" height="600" width="800"></canvas>
<script type="text/javascript" src="./js/main.js"></script>
<script type="text/javascript" src="./js/star.js"></script>
</div>
</body>
</html>
第二部写js文件
main.js
let can;
let ctx;
let w;
let h;
let img = new Image();
let jpgimage = new Image();
let num = 5;
let starArr = []
document.body.onload = () => {
can = document.getElementById('canvas')
ctx = can.getContext('2d');
w = can.width;
h = can.height;
jpgimage.src = 'src/IMG_2727 0.jpg'
img.src = 'src/star.png'
for (let i = 0 ; i < num; i++ ) {
starArr.push(new StarObj)
starArr[i].draw()
}
gameloop()
}
function drawBackground() {
ctx.fillStyle = '#303550';
ctx.fillRect(0,0, w, h)
console.log('1')
}
function gameloop() {
window.requestAnimFrame(gameloop)
drawBackground();
drawJpg()
for (let i of starArr) {
i.draw()
}
}
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);//定义每秒执行60次动画
};
})();
const drawJpg = () => {
// console.log(this)
ctx.drawImage(jpgimage, 100, 100, 600, 350)
}
start.js
class StarObj{
constructor() {
this.x = Math.floor(Math.random() * can.width);
this.y = Math.floor(Math.random() * can.height);
this.lastTime = Date.now();
this.timer = 0;
this.n = Math.floor(Math.random() * 7);
}
update() {
let space = Date.now() - this.lastTime;
this.lastTime = Date.now();
this.timer = space + this.timer;
if (this.timer > 50) {
this.n++;
this.timer = 0;
if (this.n > 7) {
this.n = 0;
}
}
}
draw() {
this.update()
ctx.drawImage(img, this.n * 7, 0, 7, 7, this.x, this.y, 7, 7)
}
}
