HTML 游戏图片
-
定义和使用
按下面的上下左右按钮移动笑脸: -
如何使用图片
为了在画布上添加图像,getContext("2d") 对象具有内置的图像属性和方法。在我们的游戏中,要将游戏片段创建为图像,请使用组件构造函数,但您必须引用图像的 url,而不是引用颜色。并且必须告诉构造函数该组件属于 "image" 类型:function startGame() { myGamePiece = new component(30, 30, "smiley.gif", 10, 120, "image"); myGameArea.start(); }
在组件构造函数中,我们测试组件是否为 “image” 类型,并使用内置的 "new image()" 对象构造函数创建一个 image 对象。当我们准备好绘制图像时,我们使用 drawImage 方法而不是 fillRect 方法:
尝试一下function component(width, height, color, x, y, type) { this.type = type; if (type == "image") { this.image = new Image(); this.image.src = color; } this.width = width; this.height = height; this.speedX = 0; this.speedY = 0; this.x = x; this.y = y; this.update = function() { ctx = myGameArea.context; if (type == "image") { ctx.drawImage(this.image, this.x, this.y, this.width, this.height); } else { ctx.fillStyle = color; ctx.fillRect(this.x, this.y, this.width, this.height); } } }
-
更改图片
您可以随时通过更改组件的 image 对象的 src 属性来更改图像。如果您想在笑脸每次移动时都更改,请在用户单击按钮时更改图像源,并在未单击该按钮时恢复正常:
尝试一下function move(dir) { myGamePiece.image.src = "angry.gif"; if (dir == "up") {myGamePiece.speedY = -1; } if (dir == "down") {myGamePiece.speedY = 1; } if (dir == "left") {myGamePiece.speedX = -1; } if (dir == "right") {myGamePiece.speedX = 1; } } function clearmove() { myGamePiece.image.src = "smiley.gif"; myGamePiece.speedX = 0; myGamePiece.speedY = 0; }
-
背景图片
通过将背景图像添加为组件,将其添加到游戏区域,并在每个帧中更新背景:
尝试一下var myGamePiece; var myBackground; function startGame() { myGamePiece = new component(30, 30, "smiley.gif", 10, 120, "image"); myBackground = new component(656, 270, "timg.jpg", 0, 0, "image"); myGameArea.start(); } function updateGameArea() { myGameArea.clear(); myBackground.newPos(); myBackground.update(); myGamePiece.newPos(); myGamePiece.update(); }
-
移动背景
更改背景组件的 speedX 属性以移动背景:
尝试一下function updateGameArea() { myGameArea.clear(); myBackground.speedX = -1; myBackground.newPos(); myBackground.update(); myGamePiece.newPos(); myGamePiece.update(); }
-
循环背景
要使相同的背景循环永远,我们必须使用一种特定的技术。首先告诉组件构造函数这是一个背景。然后,组件构造函数将添加两次映像,将第二个映像紧跟在第一个映像之后。在 newPos() 方法中,检查组件的x位置是否到达图像的末尾,如果到达,则将组件的 x 位置设置为 0:
尝试一下function component(width, height, color, x, y, type) { this.type = type; if (type == "image" || type == "background") { this.image = new Image(); this.image.src = color; } this.width = width; this.height = height; this.speedX = 0; this.speedY = 0; this.x = x; this.y = y; this.update = function() { ctx = myGameArea.context; if (type == "image" || type == "background") { ctx.drawImage(this.image, this.x, this.y, this.width, this.height); if (type == "background") { ctx.drawImage(this.image, this.x + this.width, this.y, this.width, this.height); } } else { ctx.fillStyle = color; ctx.fillRect(this.x, this.y, this.width, this.height); } } this.newPos = function() { this.x += this.speedX; this.y += this.speedY; if (this.type == "background") { if (this.x == -(this.width)) { this.x = 0; } } } }