1. 首先有一个loadImage.js
代码如下:
function loadImage(imgUrl,fn){ var imgObj = {}; var tempImg,load = 0, imgLength = 0; for(var key in imgUrl){ imgLength++; tempImg = new Image(); tempImg.onload = function () { load++; if( load >= imgLength){ fn( imgObj ); } }; tempImg.src = imgUrl[key]; imgObj[key] = tempImg; }} 2. 使画布开始动起来,也就是背景图
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <canvas id="cvs" height="500" width="500"></canvas></body><script src="js/loadImage.js"></script><script> var cvs = document.getElementById("cvs"); var ctx = cvs.getContext("2d"); function Sky( ctx, img, speed) { //debugger; this.ctx = ctx; this.img = img; this.speed = speed || 2; /*创建一个实例,length就自增*/ Sky.len++; console.log(Sky.len); this.width = this.img.width; //console.log(this.width); this.height = this.img.height; /*根据背景数量,动态计算起始的x轴坐标*/ this.x = this.width * ( Sky.len - 1 ); //console.log(this.x); //this.x = 0; this.y = 0; } /*sky实例默认的数量*/ Sky.len = 0; /*给原型扩充方法*/ Sky.prototype = { constructor: Sky, draw: function () { this.ctx.drawImage(this.img, this.x, this.y); } }</script><script> loadImage({ bird: ‘./images/bird.png‘, land: ‘./images/land.png‘, pipeDown: ‘./images/pipeDown.png‘, pipeDown: ‘./images/pipeDown.png‘, sky: ‘./images/sky.png‘ },function ( imgObj) { /*根据背景的大小设置画布的大小*/ cvs.width = imgObj.sky.width; cvs.height = imgObj.sky.height; var sky = new Sky(ctx, imgObj.sky,10); var sky2 = new Sky(ctx, imgObj.sky,10); setInterval(function () { sky.draw(); sky.x -= sky.speed; //console.log(sky.x); if( Math.abs(sky.x) >= sky.width){ sky.x += sky.width *2; } sky2.draw(); sky2.x -= sky2.speed; if( Math.abs(sky2.x) >= sky2.width){ sky2.x += sky2.width *2; } },100); })</script></html>
结果如图所示:(背景图片是运动的)
时间: 2024-10-06 02:26:57