Development of games using JavaScript and Canvas

Source: Internet
Author: User

1. Get to know Canvas

Http://www.brighthub.com/internet/web-development/articles/38364.aspx

Canvas elements and some new features in the JavaScript engine allow Web developers to design and develop sophisticated and interactive 2D Web pages without using third-party plug-ins. This article will introduce the Canvas Element and Its usage.

JavaScript and Canvas elements

HTML is generated to create a static page. The dynamic effect that HTML can achieve is limited to displaying GIF animations and flickering text. JavaScript has changed everything and can be used to dynamically modify webpages. Today, many Web services use AJAX to create webpages to provide users with a smoother experience, it also surpasses the "Click-reload-click" interactive mode, which is common in standard HTML pages.

However, some functions of JavaScript are restricted by its host browser. Although you can create and modify any element on a webpage, JavaScript cannot (easily) display a new object in a browser. It is easy to Modify text, insert images, or scale tables using JavaScript, because these objects are originally supported by HTML. What should you do if you want to play more exciting games, such as writing a web game? I'm afraid I have to worry about changing the use of standard HTML elements to overcome unexpected things. Either, you have to turn to plug-ins such as Flash or Silverlight.

The Canvas element has appeared. This new HTML element provides JavaScript developers with a mechanism to draw directly on webpages without any plug-ins. Canvas elements were first introduced by Apple in its WebKit framework. Both Safari and Dashboard are used. Currently, the Canvas element is recommended to be added to the HTML5 standard, which is supported by the latest browsers such as Chrome, Firefox, Opera, and Konqueror. Internet Explorer (at least before IE8) does not support Canvas, but the assumercanvas project provides similar features for IE and Canvas elements.

The Canvas element is a piece of cake for people who have done 2D Graphic programming. You can draw a line on this element, draw a variety of shapes, draw a gradient, or even use functions similar to other 2D APIs to modify each pixel. Thanks to the performance of Chrome V8, Firefox's SpiderMonkey, Safari's Nitro, and other latest JavaScript Engines, creating sophisticated and interactive Web applications is no longer a problem.

This series of articles will teach you how to use JavaScript and Canvas elements to create a simple platform game. The content to be involved includes animation, loading resources, layered rendering, scrolling, and interaction. By presenting sample code and actual results step by step, you can quickly learn how to control powerful Canvas elements.

2. Drawing on the Canvas

Http://www.brighthub.com/internet/web-development/articles/38744.aspx

Next, we will introduce how to use JavaScript to draw and implement animations on the Canvas element through a step-by-step example and real-time demonstration.

Preparations

After you know what the Canvas element is, you should learn to draw on the screen. First, an HTML page is required to place and display the Canvas Element.

 
 
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">  
  2.    
  3.       <title>JavaScript Platformer 1</title>  
  4.       <script type="text/javascript" src="jsplatformer1.js"></script>  
  5.       <style type="text/css">  
  6.          body { font-family: Arial,Helvetica,sans-serif;}  
  7.       </style>  
  8.    
  9.   <body>  
  10.      <p>  
  11.         <a href="http://www.brighthub.com/internet/web-development/articles/38364.aspx">  
  12.            Game Development with Javascript and the canvas element  
  13.         </a>  
  14.      </p>  
  15.      <canvas id="canvas" width="600" height="400">  
  16.         <p>Your browser does not support the canvas element.</p>  
  17.      </canvas>  
  18.   </body>  
  19. /html> 

These HTML codes are intuitive. There are two important elements.

 
 
  1. <script type="text/javascript" src="jsplatformer1.js"></script> 

Here, the JavaScript code of the Canvas element will be modified. The corresponding Canvas Element is marked as follows:

 
 
  1. <canvas id="canvas" width="600" height="400">  
  2.     <p>Your browser does not support the canvas element.</p>  
  3. </canvas>  

The code above creates a Canvas element. Canvas browsers are not supported, such as Internet Explorer (earlier than IE8). This element is ignored and only its child elements are displayed. In this simple example, the child element is a paragraph, and the text tells the user that their browser does not support the Canvas Element. For browsers that support Canvas elements, such as Chrome, Opera, and Firefox, child elements of the Canvas element are ignored.

The ID attribute of this Canvas element is very important, because the JavaScript will use it to get reference to this element. The width and height attributes specify the width and height of the canvas, which are the same as those of other HTML elements such as table or img.

The following is the jsplatformer1.js code:

 
 
  1.  
  2. // Target frame per second
  3. Const FPS = 30;
  4. Var x = 0;
  5. Var y = 0;
  6. Var xDirection = 1;
  7. Var yDirection = 1;
  8. Var image = new Image ();
  9. Image. src = "jsplatformer1-smiley.jpg ";
  10. Var canvas = null;
  11. Var context2D = null;
  12.  
  13. Window. onload = init;
  14. Function init (){
  15. Canvas = document. getElementById ('canvas ');
  16. Context2D = canvas. getContext ('2d ');
  17. SetInterval (draw, 1000/FPS );
  18. }
  19. Function draw (){
  20. Context2D. clearRect (0, 0, canvas. width, canvas. height );
  21. Context2D. drawImage (image, x, y );
  22. X + = 1 * xDirection;
  23. Y + = 1 * yDirection;
  24.  
  25. If (x >=450 ){
  26. X = 450;
  27. XDirection =-1;
  28. } Else if (x <= 0 ){
  29. X = 0;
  30. XDirection = 1;
  31. }
  32. If (y> = 250 ){
  33. Y = 250;
  34. YDirection =-1;
  35. } Else if (y <= 0 ){
  36. Y = 0;
  37. YDirection = 1;
  38. }
  39. }

It is useless if it is just a Canvas element. JavaScript must draw something on the canvas, and the corresponding code is saved in jsplatformer1.js. Simply put, JavaScript loads an image here, draws it on the canvas, and finally moves it on the canvas.

First, define some global variables.

 
 
  1. const FPS = 30;  

FPS defines the canvas re-painting frequency.

 
 
  1. var x = 0;  
  2. var y = 0;  
  3. var xDirection = 1;  
  4. var yDirection = 1; 

Variables x, y, xDirection, and yDirection are used to define the position of an image (relative to the upper left corner of the canvas) and the direction in which it moves at any time.

 
 
  1. var image = new Image();  
  2. image.src = "http://javascript-tutorials.googlecode.com/files/jsplatformer1-smiley.jpg"; 

To draw an image onto the canvas, you must first load an image. Therefore, we create an Image object and set its src attribute to the URL of an Image file (we recommend that you download the Image to your local device. -- Translator's note ).

 
 
  1. var canvas = null;  
  2. var context2D = null; 

We also need to get reference to the Canvas element and the drawing context (which will be detailed later. Later, we will assign the correct values to these two variables. Now we need to set them to null.

 
 
  1. window.onload = init; 

Finally, when the page is loaded, we must know that the code for drawing the canvas is run immediately. Therefore, when the onload event of the window object occurs, the init function is called immediately.

Init Function

 
 
  1. function init(){  
  2.     canvas = document.getElementById('canvas');  
  3.     context2D = canvas.getContext('2d');  
  4.     setInterval(draw, 1000/FPS);  
  5. }  

After the page is loaded, the above init function will be called. In this function, we first get the Canvas Element Through the ID attribute specified in the HTML file (without a doubt, what can it be called besides the canvas ?), Then obtain the 2D drawing context object of the canvas.

The context object is used to define how to draw on the canvas. As the name implies, 2D context supports drawing 2D images, images, and text on the canvas. Browsers that support Canvas elements all support 2D context. In addition to 2D context, there are other experimental context objects. Opera has a 2D context specifically designed for games, while Mozilla has a context that can display 3D scenes. Unfortunately, these context objects are currently only supported by specific browsers. If you want to use a canvas to create a Web application, you 'd better use only the common 2D context.

Because we want to draw a moving image here, we must create a rendering loop ). The so-called rendering loop is actually a function called repeatedly. every iteration of the rendering loop (in this example) can make the image shift a little on the screen, this round-robin can give people the feeling of moving images. Therefore, we call the setInterval function. Its first parameter is the function that should be called repeatedly. The function name here is draw. The second parameter of the setInterval function specifies the frequency of calling the function. The unit of this parameter value is millisecond, and the number of milliseconds between each call is obtained by dividing 1000 by the FPS defined earlier.

Note that although we specify to call the draw function 30 times per second, it will not actually call 30 times. How long the draw function is called depends on the speed of the underlying JavaScript engine and the complexity of the draw function code to be executed. If the system is slow, it is likely that the draw function can be called only once per second. Therefore, the frequency specified for setInterval is the most ideal situation.

Draw Function

Drawing operations on the canvas are actually completed by the draw function. Next we will describe the plotting operations step by step.

 
 
  1. context2D.clearRect(0, 0, canvas.width, canvas.height); 

All plotting operations occur on the context object, not on the canvas element. First, clear the context to prepare a clean layout for each frame.

 
 
  1. context2D.drawImage(image, x, y); 

Then, the image is drawn to the context object. Parameters x and y specify the coordinates in the upper left corner of the image.

 
 
  1. x += 1 * xDirection;  
  2. y += 1 * yDirection; 

To move the image on the canvas, You need to determine whether xDirection and yDirection are equal to 1 (to the right or down) or equal to-1 (to the left or up ), to increment or decrease the values of x and y.

 
 
  1. if (x >= 450){  
  2.     x = 450;  
  3.     xDirection = -1;  
  4. } else if (x <= 0) {  
  5.     x = 0;  
  6.     xDirection = 1;  
  7. }  
  8. if (y >= 250) {  
  9.     y = 250;  
  10.     yDirection = -1;  
  11. } else if (y <= 0) {  
  12.     y = 0;  
  13.     yDirection = 1;  

If the image is moved outside the canvas, the orientation of the image is reversed. We know that the image size is 150x150 pixels, while the canvas size is 600x400 pixels, so there is 450 (600-150) and 250 (400-150) these two values.

The final effect is that the smiling face image will rebound in the canvas. At this moment, some readers may think that it is easier to achieve the same effect by modifying the position of the DIV element. I do not deny this. However, this example only demonstrates the simple effects of Canvas elements. In the next article, we will introduce the advanced effects that can be achieved by using Canvas elements. If other effects are used, it may be much more difficult.

Author: Matthew Casperson Original article link: Game Development with JavaScript and the Canvas element

Li songfeng (http://www.cn-cuckoo.com/2011/08/10/game-development-with-javascript-and-the-canvas-element-2554.html)

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.