MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to work with HTML5 Canvas API transformations

In this article we will talk about the HTML5 Canvas API transformations. We will see how easily is add a canvas element in the HTML page using a basic markup

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction

The main purpose of the HTML5 canvas element is to manipulate 2-D graphics, even 3-D graphics in the near future. Using the canvas element and JavaScript API you can create pretty amazing dynamic graphics and animations that can react to the user’s input.

Content

You can easily add a canvas element in the HTML page using a basic markup like this:

Listing 1: Adding a canvas element in the HTML

<canvas id=”myCanvas” width="600" height="500">
<!-- Insert fallback content here -->
</canvas>

If you omit the width and height attributes, the canvas will have, by default, the width 300px and the height 150px. Practically, the markup above won’t do anything visible in your page because the canvas element acts like a container for the 2-D rendering context which is a standard screen-based platform that uses the Cartesian coordinate system with the point origin (0,0) located in the top-left corner of the canvas. You can access the 2-D rendering context using plain JavaScript like this:

Listing 2: Accessing the 2-D rendering content using JavaScript

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

Or by using JQuery like this:

Listing 3: Using jQuery

var canvas = $("#myCanvas");
var context = canvas.get(0).getContext("2d");

In this point the variable called context contains the 2-D rendering context and we can start drawing.

If you want to make the canvas fill the browser window, you have to use some JQuery lines like that:

Listing 4: Using jQuery to fill the browser window

var canvas = $("#myCanvas");
var context = canvas.get(0).getContext("2d");
canvas.attr("width", $(window).get(0).innerWidth);
canvas.attr("height", $(window).get(0).innerHeight);

You will notice that the canvas is still surrounded by a white border which can be eliminated using a bit of CSS:

Listing 5: Eliminating white border using CSS

<style>
* {
		margin:0;
		padding: 0;
	}
	html, body {
		width:100%;
		height:100%;
	}
	canvas {
		display: block;
	}
</style>

Now the canvas is filling the browser window but if you try to re-size the browser, the canvas won’t automatically adjust to the new window and it will display scrollbars. To fix this issue, you can use the JQuery resize method which is triggered when the browser window is resized. You can use the resize method to call a custom function which will adjust the canvas size. If you want to actually see what’s happening with the canvas, you can add in this custom function the fillRect method to draw a black rectangle with same size as your canvas.

The HTML code for this page is presented below:

Listing 6: Displaying HTML Code

<!DOCTYPE html>
<html>
	<head>
		<title>Making canvas fill the browser window</title>
		<meta charset="utf-8">
		<style>
			* {
				margin:0;
				padding: 0;
			}
			html, body {
				width:100%;
				height:100%;
			}
			canvas {
				display: block;
			}
		</style>
		<script src="jquery.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				var canvas = $("#myCanvas");
				var context = canvas.get(0).getContext("2d");
				$(window).resize(resizeMyCanvas);
				function resizeMyCanvas() {
					canvas.attr("width", $(window).get(0).innerWidth);
					canvas.attr("height", $(window).get(0).innerHeight);
					context.fillRect(0, 0, canvas.width(), canvas.height());
				};
				resizeMyCanvas(); //draw initial rectangle
			});
		</script>
	</head>
	<body>
		<canvas id="myCanvas">
			<!-- Insert fallback content here -->
		</canvas>
	</body>
</html>

As you can see from the code above, every time the browser window is resized, the resize method will call the resizeMyCanvas function which will get the current width and height of the browser window and will set up the canvas dimensions, then it will draw a black (default color) rectangle as large as the canvas element. When the DOM is loaded, the resizeMyCanvas function is called to draw the initial rectangle.

The canvas transformations allow you to directly manipulate the coordinate system. The Canvas API defines three basic transformations: scale(), rotate() and translate() which are applied through the 2-D rendering context of canvas.

To scale an object you must provide two arguments which represent the scaling factors for the x, respectively the y coordinate: context.scale( factor_x, factor_y);

For example, the code below will scale your drawn object to 60% of its original size: context.scale(0.6, 0.6);

To rotate an object you must provide the rotation clockwise angle in radiant: context.rotate(rotation_angle);

For example, the code below will rotate your objects 90 degrees clockwise: context.rotate(0.5);

If you want to rotate the object in reverse clockwise order, you have to use a negative value for the argument.

To translate an object along with the origin of the coordinate system, you must provide an x, respectively on y offset for the new origin: context.translate(offset_x, offset_y);

For example, the code below will moved the object and the origin of the coordinate system with 100 pixels to right and 70 pixels down.: context.translate(100,70);

If you want to combine these transformations, in JavaScript you must call the transform methods in reverse order. So if you want to scale, translate and then rotate an image, the calling order in JavaScript is:

Listing 7: Calling order in JavaScript to scale, translate and image rotation

context.rotate(angle);
context.translate(x_offset,y_offset);
context.scale(x_factor, y_factor);

The next example illustrates the use of canvas transformation to achieve a spectacular image effect:

Listing 8: Using Canvas transformation

<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Using the HTML5 canvas transformations</title>
</head>
<body>
<figure>
  <canvas id="myCanvas" width="1200" height="800" style="border: 1px solid black;">
    We are sorry, but your browser doesn't support the canvas element.
  </canvas>
</figure>

  <script>
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");

    var image = new Image();
    image.src = 'landscape.jpg';

    image.onload = function() {
      var rotate = 15;
      var scaleStart = 0.0;
      var scaleEnd = 4.0;
      var scaleInc = (scaleEnd-scaleStart)/(360/rotate);
      var s = scaleStart;
      for (var i=0; i<=360; i+=rotate) {
        s += scaleInc;
        context.translate(540,260);
        context.scale(s,s);
        context.rotate(i*-1* Math.PI / 180); //negative rotation angle
        context.drawImage(image,0,0,120,80);
        context.setTransform(1,0,0,1,0,0);
      }
    };
  </script>
</body>
</html>
Displaying Spectacular Image Effect

Figure 1: Displaying Spectacular Image Effect

In the presented example all JavaScript code is placed in onload event of the image, so it will be executed as soon as the image is completely loaded. The rotation angle is set to 15 degrees counterclockwise so the image will be rotated 24 times to complete a full circle. Because the rotation is counterclockwise, we need a negative radiant rotation angle and the formula for the rotation angle is i*(-1)*PI/180, where i the order number of the rotation. The image is scaled at every rotation between a start scale of 0 and an end scale of 4. To calculate the scale increment factor we can use the formula (scaleEnd-scaleStart) /(360/rotate) and for the given values it will be 1/6 so at every rotation the new image it will be with 16,(6)% bigger than the last image. At every step, the image is rotated 15 degrees counterclockwise, is scale to 116,(6)% from previous image and then is translated in the point (540,260) so all the images will have the top-left corner in the same point creating the spiral effect.

As you can see in the code above, the last JavaScript line invokes the setTransform method of the 2-D rendering context. The basic transformations scale(), rotate() and translate(), they all affect a so called the transformation matrix. This matrix has three rows and three columns, but only the first two rows can be manipulated through cod. The first line contains the values: x_scale, x_skew, x_translate, while the second row contains the values: y_scale, y_skew and y_translate. Every new 2-D rendering context it will have a transformation matrix with x_scale=y_scale=1 and x_skew=y_skew=x_translate= y_translate=0. This fresh matrix is called identity matrix and it means that no transformation is performed. The transformation matrix values can be manipulating with the context.transform and the context.setTransform methods. Both methods take six arguments : x_scale, x_skew, x_translate, y_scale, y_skew, y_translate, in this exact order.

Looking again at the last JavaScript line of code, we can understand know that after each step (rotate, scale and transform image), the transformation matrix is reset to the identity matrix because the scale and rotate angle are calculated with formulas relative to the start image not relative to the previous image.

Conclusion

The new HTML5 canvas element offers a native support for creating and manipulating graphics and images so that amazing interactive web pages can be created using only the Canvas and JavaScript API.



Working in Software Development domain from 7 years now and is well equipped with programming languages like HTML, CSS, Java, PHP, .NET etc.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login