HTML5 game development Technology base finishing

Source: Internet
Author: User

With the final finalization of the HTML5 standard, HTML5 will be expected to become a popular platform in the field of game development. HTML5 games can be run on computers, smartphones and tablets, including the iphone and ipad series, and are the best implementations for cross-platform application development today. This article is based on [HML5 Canvas game development Combat] in the content of the book, is to understand and learn the basic content of HTML5 game development, and hope to help those who are like bloggers dedicated to game development friends!

Object-oriented programming in JavaScript

Object-oriented Programming (OOP) is an important and necessary method for game development, so you should first understand object-oriented programming in JavaScript before understanding HTML5 game development. JavaScript is an object-based language, but it is not a true object-oriented programming language, because the concept of class is not present in JavaScript syntax. Below we will analyze and resolve object-oriented issues such as encapsulation, inheritance, and so on in JavaScript.

In JavaScript, a function is just a class.
//声明一个函数function MyClass(){}//实例化一个对象varnew MyClass();
You can add properties to a class by using the This keyword
//声明一个类并定义其构造函数function MyClass(name,age){    this.name = name;    this.age  = age;};//实例化一个对象varnew MyClass("张三",20)//输出cls1的两个属性值alert("name=""&" + cls1.age)
Use the prototype property to add a method to a class
//Declare a class and define its constructors function MyClass(name,age){     This. name = name; This. Age = Age;};//For MyClass Add methodmyclass.prototype={toString: function() {Alert"Name="+ This. Name +"&"+ This. Age)}, GetName: function() {Alert"Name="+ This. Name)}, Getage: function() {Alert"Age="+ This. Age)}};
Using the Apply method to implement inheritance of properties and methods
//Define a parent class people function people(){     This. type="People"};//Define a method for the parent classpeople.prototype={GetType: function() {Alert"Type="+ This. Type)}};//define a subclass student function Student(name,age,sex){   //Inherit the property of the parent class typePeople.apply ( This,arguments); This. name = name; This. Age = Age; This. sex = sex;};//Declare a student instancevarStu =NewStudent ("Zhang San", -,"Male");//Output TypeAlert (Stu.type)let's see how to inherit the parent class method, the inherited parent method is implemented primarily by looping through the prototype of the parent object, as//Redefine subclass student function Student(name,age,sex){    //Inherit the property of the parent class typePeople.apply ( This,arguments);//Inherit methods from parent class, slightly abstract   varProp for(PropinchPeople.prototype) {varProto = This. Constructor.prototype;if(!proto[prop])        {Proto[prop] = People.prototype[prop]; } proto[prop]["Super"] = People.prototype; }//attribute definition    This. name = name; This. Age = Age; This. sex = sex;};//Instantiate Student objectvarStu =NewStudent ("Zhang San", -,"Male"); Stu.gettype ();
Implementation of static classes
function staticClass(){    "张三";    staticClass.toString=function    {        alert("name=" + staticClass.name )    };};alert(staticClass.name);staticClass.toString();
Canvas Drawing Basics

HTML5 provides new features such as image, video, audio, form, location, local database, offline storage, websocket, etc., and for HTML game development, we focus on image, audio, local database and websocket, etc. First, let's look at the basics of the next Canavs drawing.

Canvas is a canvas that HTML5 gives us, allowing us to draw graphics directly on the HTML, so canvas can be a basic element of HTML5 game development-the bottom of the HTML5 game engine is driven by the canvas elements. The canvas itself does not have the ability to draw, and it requires JavaScript to implement the drawing functionality. Using a canvas element simply adds a canvas tag to the page, such as

<canvas id="myCanavs" width="800" height="480"></canvas>

We then use JavaScript to get the canvas and initialize the drawing environment with the relevant API

//获取Canvas元素canvas = document.getElementById(‘myCanvas‘);//检查canvas合法性if(canvascanvas.getContext){    //获取当前上下文    canvas.getContext(‘2d‘)    }

Because the canvas currently supports only 2D drawings, the parameters here are only temporarily 2d. Because the API for the Cnavas drawing is encapsulated in the CTX instance, all of the following operations are done based on CTX:

Draw a line using canvas
//设置线宽10;//设置画笔颜色"red";//创建一个路径ctx.beginPath();//路径起点ctx.moveTo(10,10);//路径终点ctx.lineTo(150,50);//绘制路径ctx.stroke();
Draw a rectangle using Cnavas
//设置线宽ctx.lineWidth=5;//设置画笔颜色ctx.strokeStyle-"red"//创建路径ctx.beginPath();//绘制矩形ctx.strokeRect(10,10,70,40);

Or

//定义矩形ctx.rect(10,10,70,40);//绘制矩形ctx.stroke();

If you need to fill a rectangle

//创建路径ctx.beginPath()//绘制矩形ctx.fillRect(10,10,70,40)
Draw a circle using canvas
//创建路径ctx.beginPath();//定义圆ctx.arc(100,100,50,0,360*Math.PI/180,true);//绘制圆ctx.stroke();

Similarly, you can use fill to populate the drawing

//创建路径ctx.beginPath();//定义圆ctx.arc(100,100,50,0,360*Math.PI/180,true);//绘制圆ctx.fill();
Draw rounded rectangles using canvas

Drawing rounded rectangles requires arcto functions with LineTo to complete

Create Path CTX. Beginpath();CTx. MoveTo( +, -);CTx. LineTo( -, -);CTx. ArcTo( -, -, -, +, -);CTx. LineTo( -, -);CTx. ArcTo( -, -, -, -, -);CTx. LineTo( +, -);CTx. ArcTo( -, -, -, -, -);CTx. LineTo( -, +);CTx. ArcTo( -, -, +, -, -);Draw Rounded Rectangle CTX. Stroke();
Drawing complex graphics using canvas

In HTML5, you can draw two Bezier curves through the Quadraticcurveto function and draw three Bezier curves with the Beziercurveto function, please refer to the API documentation for the specific code.

Draw text Using canvas
//设置字体ctx.font="30px Arial";//绘制文字ctx.strokeText("Hello HTML5",100,50);
Draw a picture using canvas

To draw a picture using the DrawImage function, its function is prototyped as follows:

drawImage(image,dx,dy);

Where image can be a label in HTML or an Image object in JavaScript. Such as

//定义一个img标签id="img_source" src="source.jpg" width="240" height="240"/>

The next step is to get the image data by getElementById and draw it out.

var img=document.getElementById("img_source");ctx.draw(img,200,200);

If you use JavaScript code directly

var img=new Image();img.src="source.jpg";ctx.draw(img,200,200)
Panning Operations for graphics

Use the Translate function for panning in both horizontal and vertical directions

Rotation operation of the graph

Using the Rotate function for rotation, it is important to note that the parameters passed in are radians

Scaling Operations for graphics

Use the scale function for scaling, which means flipping in that direction when the argument is negative

Graphics Advanced Effects

Here we mainly introduce linear gradient, radial gradient, color inversion, grayscale.

Linear gradient
//创建一个线性渐变容器var grd=ctx.createLinearGradient(0,0,200,0);//添加颜色grd.addColorStop(0.2,"#00ff00");grd.addColorStop(0.8,"#ff0000");//应用渐变ctx.fillStyle=grd;
Radial gradient
//创建一个径向渐变容器var grd=ctx.createRadialGradient(100,100,10,100,100,50);//添加颜色grd.addColorStop(0,"#00ff00");grd.addColorStop(,"#ff0000");//应用渐变ctx.fillStyle=grd;
Color reversal

Iterate through each pixel and reverse the RGB values

Gray

Grayscale Calculation formula: gary=red*0.3+green*0.59+blue*0.11

This is the basis of the content, if you encounter the need to HTML5 the place can look back.

HTML5 game development Technology base finishing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.