Use Canvas to develop games using JavaScript and Canvas

Source: Internet
Author: User
Tags translate function

3. Advanced Image operations through the Canvas Element

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

This article will teach you how to use JavaScript and Canvas elements to operate images in several different ways. These methods are impossible before the appearance of the Canvas element.

The previous article demonstrated how to use Canvas to implement a basic image animation. The example is very simple. The same effect can be easily implemented by modifying some attributes of standard HTML elements such as IMG or DIV. Next we will demonstrate the advanced application of the Canvas Element and Its real power.

First, prepare an HTML page.

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

Compared with the HTML page in the previous example, the only difference is that some buttons are added. Click these buttons to set the value of the currentFunction variable (described later) to change the function running in the rendering loop.

The following is the jsplatformer2.js code.

 
 
  1.  
  2. // The number of frames per second
  3. Const FPS = 30;
  4. Const SECONDSBETWEENFRAMES = 1/FPS;
  5. Const HALFIMAGEDIMENSION = 75;
  6. Const HALFCANVASWIDTH = 300;
  7. Const HALFCANVASHEIGHT = 200;
  8. Var image = new Image ();
  9. Image. src = "jsplatformer2-smiley.jpg"; // still the image in the first example
  10. Var canvas = null;
  11. Var context2D = null;
  12. Var currentFunction = null;
  13. Var currentTime = 0;
  14. Var sineWave = 0;
  15.  
  16. Window. onload = init;
  17.  
  18. Function init ()
  19. {
  20. Canvas = document. getElementById ('canvas ');
  21. Context2D = canvas. getContext ('2d ');
  22. SetInterval (draw, SECONDSBETWEENFRAMES * 1000 );
  23. CurrentFunction = scale;
  24. }
  25.  
  26. Function draw ()
  27. {
  28. CurrentTime + = SECONDSBETWEENFRAMES;
  29. SineWave = (Math. sin (currentTime) + 1)/2;
  30.  
  31. Context2D. clearRect (0, 0, canvas. width, canvas. height );
  32.  
  33. Context2D. save ();
  34.  
  35. Context2D. translate (HALFCANVASWIDTH-HALFIMAGEDIMENSION, HALFCANVASHEIGHT-HALFIMAGEDIMENSION );
  36.  
  37. CurrentFunction ();
  38.  
  39. Context2D. drawImage (image, 0, 0 );
  40.  
  41. Context2D. restore ();
  42. }
  43.  
  44. Function alpha ()
  45. {
  46. Context2D. globalAlpha = sineWave;
  47. }
  48.  
  49. Function shear ()
  50. {
  51. Context2D. transform (1, 0, (sineWave-0.5), 1, 0, 0 );
  52. }
  53.  
  54. Function scale ()
  55. {
  56. Context2D. translate (HALFIMAGEDIMENSION * (1-sineWave), HALFIMAGEDIMENSION * (1-sineWave ));
  57. Context2D. scale (sineWave, sineWave );
  58. }
  59.  
  60. Function rotate ()
  61. {
  62. Context2D. translate (HALFIMAGEDIMENSION, HALFIMAGEDIMENSION );
  63. Context2D. rotate (sineWave * Math. PI * 2 );
  64. Context2D. translate (-HALFIMAGEDIMENSION,-HALFIMAGEDIMENSION );
  65. }

As before, this JavaScript file first defines some global variables.

◆ FPS: the number of frames per second

◆ SECONDSBETWEENFRAMES: the number of seconds between two frames (the reciprocal of FPS)

◆ HALFIMAGEDIMENSION: half the width/height of the image to be drawn, which is used to locate the image to the center of the canvas

◆ HALFCANVASWIDTH: half the width of the canvas. It is used in combination with HALFIMAGEDIMENSION to center the image on the canvas.

◆ HALFCANVASHEIGHT: half of the canvas height, used in combination with HALFIMAGEDIMENSION to center images on the canvas

◆ CurrentFunction: The function running in the rendering loop (see the previous article ).

◆ CurrentTime: How many seconds has the application been running

◆ SineWave: A value between 0 and 1, used to control Image Motion

◆ Image: image to be drawn on the canvas

◆ Canvas: canvas Element reference

◆ Context2D: reference of the 2D context of the Canvas Element

Then, as before, you need to call the init function immediately when the onload event of the window occurs (for more information about the init function, see the previous article ).

Draw Function

Let's take a look at the draw function:

 
 
  1.  
  2. function draw()  
  3. {  
  4.     currentTime += SECONDSBETWEENFRAMES;  
  5.     sineWave = (Math.sin(currentTime) + 1) / 2;  
  6.  
  7.     context2D.clearRect(0, 0, canvas.width, canvas.height);  
  8.  
  9.     context2D.save();  
  10.     context2D.translate(HALFCANVASWIDTH - HALFIMAGEDIMENSION, HALFCANVASHEIGHT - HALFIMAGEDIMENSION);  
  11.     currentFunction();  
  12.     context2D.drawImage(image, 0, 0);  
  13.     context2D.restore();  
  14. }  

This example demonstrates four effects: modifying the alpha value (transparency) and scaling, rotating, and shear images. To demonstrate these effects, you need to apply changes based on values within a certain range. The variable sineWave is used to define the reference of this range value.

The standard sine function can generate a perfect waveform between-1 and 1. First, we increase the currentTime variable to reflect how long the animation has been running, and then use this value to find a point on the sine curve. Add 1 to the values returned by the sine function (from-1 to 1) and divide them by 2 to convert them into values in the range of 0 to 1.

 
 
  1. currentTime += SECONDSBETWEENFRAMES;  
  2. sineWave = (Math.sin(currentTime) + 1) / 2; 

Call the clearRect method to clear the canvas to prepare a clean layout for the subsequent drawing.

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

The effects applied to the canvas can be accumulated, so you can use a few simple functions to "combine" the effects. For example, a ship may need to be rotated, transformed, or scaled before being drawn to the screen. Because all effects work on the canvas, these effects apply to all objects that will be drawn on the screen, not just an image or a shape (such as a ship ).

Among them, the save and restore functions provide a simple mechanism for applying these cumulative effects to draw images or images that apply these effects to the canvas, then, "undo" these changes. What are background operations? The save Function pushes the current drawing status to the stack, while the restore function pushes the last status to the stack. Taking the spacecraft mentioned above as an example, you need to perform the following operations:

◆ Call the save Function to save the current drawing status)

◆ Rotating, transforming, and scaling the context

◆ Drawing a ship

Call the restore function to remove any effect added since the last time the save method was called, that is, to undo previous changes.

Here, we need to combine these two methods. First, save the painting status before applying any effects to the canvas.

 
 
  1. context2D.save(); 

After the rendering status is saved, the target effect of the application is displayed. Therefore, call the translate function to center the subsequent image on the canvas.

 
 
  1. context2D.translate(HALFCANVASWIDTH - HALFIMAGEDIMENSION, HALFCANVASHEIGHT - HALFIMAGEDIMENSION); 

Next, call the function referenced by the variable currentFunction. These referenced functions are the key to making the image alpha (transparency) change, scaling, rotation, and shear. We will introduce these functions later.

 
 
  1. currentFunction(); 

After applying the effect to the image, you can draw it on the canvas. Therefore, the next step is to call drawImage for plotting.

 
 
  1. context2D.drawImage(image, 0, 0);  

Finally, call the restore function to remove all effects applied since the save function is called from the canvas.

 
 
  1. context2D.restore(); 

Alpha Function

 
 
  1. function alpha()  
  2. {  
  3.     context2D.globalAlpha = sineWave;  

By modifying the globalAlpha attribute of the context object, the transparency of all subsequent painting operations will be modified. Setting globalAlpha to 0 means that any object to be drawn will be completely transparent. setting this attribute to 1 means that any painting operation will maintain the original transparency level. Here, we can modify the globalAlpha attribute to fade in and out smiling faces.

Shear Function

 
 
  1. function shear()  
  2. {  
  3.     context2D.transform(1, 0, (sineWave - 0.5), 1, 0, 0);  
  4. }  

The shear operation is implemented by applying a matrix to the canvas through the transform function. Transformation Matrix itself is a topic worth studying, but for us, if you don't want to understand the mathematical principles behind, you can find a lot of standard 2D transformation matrix (http://en.wikipedia.org/wiki/Transformation_matrix#Examples_in_2D_graphics) on the Internet ), directly use the transform function to apply them. The so-called shear is actually pushing the top or bottom of the image to one side.

Scale Function

 
 
  1. function scale()  
  2.  {  
  3.      context2D.translate(HALFIMAGEDIMENSION * (1 - sineWave), HALFIMAGEDIMENSION * (1 - sineWave));  
  4. 56  
  5.     context2D.scale(sineWave, sineWave);  
  6.  }  

As the name suggests, the scale function modifies the image size. But before that, we also called a transalte function. This is to center the scaled image on the canvas. If you comment out this line of code, you will find that the image expands from the upper left corner to the lower right corner. Call the translate function to offset the displacement of the center and keep the image centered.

Rotate Function

 
 
  1. function rotate()  
  2. {  
  3.     context2D.translate(HALFIMAGEDIMENSION, HALFIMAGEDIMENSION);  
  4.     context2D.rotate(sineWave * Math.PI * 2);  
  5.     context2D.translate(-HALFIMAGEDIMENSION, -HALFIMAGEDIMENSION);  
  6. }  

Similar to the scale function, the rotate function acts as its name: rotating an image. Similar to the scale function, the translate function is also called here to ensure that the image rotates around the center rather than the upper left corner. We recommend that you comment out the call to the translate function and check whether the results are different.

Just now we have seen four simple effects implemented by using Canvas elements. These effects are almost impossible to use standard HTML elements. Some effects can be implemented using built-in functions such as scale and rotate, while using the transform function can complete a large number of image operations (shear is only one of them ).

Let's take a look at the Demo. Http://webdemos.sourceforge.net/jsplatformer2/jsplatformer2.html

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.