AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > html游戏

html教程之游戏组件--在游戏区域添加一个红色方块

51自学网 http://www.51zixue.net

 在游戏区域添加一个红色方块:


添加组件

制作一个组件构造函数,它可以让您将组件添加到游戏区。


对象构造函数被称为组件,我们制作了第一个组件,名为myGamePiece:


var myGamePiece;

function startGame() {
    myGameArea.start();
    myGamePiece = new component(3030"red"10120);
}

function component(width, height, color, x, y) {
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y; 
    ctx = myGameArea.context;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
}

组件具有控制其外观和动作的属性和方法。

完整源代码:<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>

canvas {

    border:1px solid #d3d3d3;

    background-color: #f1f1f1;

}

</style>

 

 

</head>

<body onload="startGame()">

<script>

 

var myGamePiece;

 

function startGame() {

    myGameArea.start();

    myGamePiece = new component(30, 30, "red", 10, 120);

}

 

var myGameArea = {

    canvas : document.createElement("canvas"),

    start : function() {

        this.canvas.width = 480;

        this.canvas.height = 270;

        this.context = this.canvas.getContext("2d");

        document.body.insertBefore(this.canvas, document.body.childNodes[0]);

    }

}

 

function component(width, height, color, x, y) {

    this.width = width;

    this.height = height;

    this.x = x;

    this.y = y;    

    ctx = myGameArea.context;

    ctx.fillStyle = color;

    ctx.fillRect(this.x, this.y, this.width, this.height);

}

 

</script>

 

<p>We have added a component to our game, a red square!</p>

 

</body>

</html>

查看网页效果>>

 


 
上一篇:认识游戏画布--canvas  下一篇:html教程之游戏组件--帧