游戏的背景图如果是动态的, 效果会好很多, 最简单的做法是让背景图有一种卷轴效果,即看起来背景图一直是从上往下,或者从右往左移动.以前用python 做过,这里把python 写为Javascript就可以了。 主要是用到Javascript 的drawImage()。 把任一背景图与以.html 的程序放在一个文件夹就可以运行。 代码如下:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- The canvas for the panning background -->
<canvas id="background" width="600" height="360">
Your browser does not support canvas. Please try again with a different browser.
</canvas>
<script>
var bkground_img=new Image();
var canvas = document.getElementById("background");
var ctx = canvas.getContext("2d");
bkground_img.src="space_bg.png";
class Background {
constructor(img,ctx,canvas,vert) {
this.img=img;
this.ctx=ctx;
this.canvas=canvas;
this.vert=vert;
this.x=0;
this.y=0;
this.speed=0.5;
}
draw(){
if (this.vert) {
this.y+=this.speed;
this.ctx.drawImage(this.img,this.x,this.y,this.canvas.width,this.canvas.height);
this.ctx.drawImage(this.img,this.x,this.y-this.canvas.height,this.canvas.width,this.canvas.height);
if (this.y>=this.canvas.height) this.y=0;
}
else {
this.x-=this.speed;
this.ctx.drawImage(this.img,this.x,this.y,this.canvas.width,this.canvas.height);
this.ctx.drawImage(this.img,this.x+this.canvas.width,this.y,this.canvas.width,this.canvas.height);
if (this.x<=-this.canvas.width) this.x=0;
}
}
}
bk=new Background(bkground_img,ctx,canvas,1);
function animate() {
window.requestAnimationFrame(animate);
bk.draw();
}
animate();
</script>
</body>
</html>
|