HTML 5 Canvas – the 2D context – part 1

The getContext() method of a canvas element is invoked with 2d as the argument, a CanvasRenderingContext2D object is returned (canvas_2D in the example below).

<script type="application/javascript">
function draw() {
  var canvas_2D = document.getElementById("canvas");
  var ctx = canvas_2D.getContext("2d");
}
   </script>
There MUST BE only one CanvasRenderingContext2D object per canvas, therefore by calling getContext() with the 2d argument a second time will return the same object. Cartesian surface at coordinate (0,0) at the top left corner is used to display 2D context.

A drawing states of a 2D canvas context contain:
  • The transformation matrix.
  • The clipping region.
  • The values of the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin,miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font,textAlign, textBaseline.

You can use context.save() to push a copy of the current drawing state onto the drawing state stack and context.restore() to pop the top entry in the drawing state stack, and reset the drawing state. The method does nothing if it’s empty state.


Context Transformations

he transformation matrix is applied to coordinates when creating shapes and paths.

When the context is created, the transformation matrix must initially be the identity transform. It may then be adjusted using the transformation methods.

The transformations must be performed in reverse order. For instance, if a scale transformation that doubles the width is applied, followed by a rotation transformation that rotates drawing operations by a quarter turn, and a rectangle twice as wide as it is tall is then drawn on the canvas, the actual result will be a square.

context.scale(x, y) is to add the scaling transformation to the transformation matrix. The x and y arguments represent the scale factor in the horizontal direction and in the vertical direction. The factors are multiples.

context.rotate(angle_to_rotate) is to add the rotation transformation to the transformation matrix. The angle_to_rotate argument shows a clockwise rotation angle in radians.

context.translate(x, y) is to add the translation transformation to the transformation matrix. The x and y arguments represent the translation distance in the horizontal direction and in the vertical direction. The arguments are in coordinate space units.

context.transform(m11, m12, m21, m22, dx, dy) is to multiply the current transformation matrix with the matrix described by:

m11 m21 dx

m12 m22 dy

0 0 1

context.setTransform(m11, m12, m21, m22, dx, dy) is to reset the current transform to the identity matrix, and invoke the transform(m11, m12, m21, m22, dx, dy) method with the same arguments.

Color and Style in HTML 5 canvas

context.strokeStyle = StrokeValue

The above method is to set or to change the stroke style of a canvas context. The style could be a string containing a CSS color, or a CanvasGradient or CanvasPattern object.

context.fillStyle  = FillValue

The above method is to set or to change the fill style. The style can be a string containing a CSS color, or a CanvasGradient or CanvasPattern object.

Shadow in HTML 5 canvas

context.shadowColor = ShadowColorValue

The above method is to set, to change or to return the shadow color. Values that cannot be parsed as CSS colors are ignored.

context.shadowOffsetX = OffsetXvalue

context.shadowOffsetY = OffsetYvalue

Can be set, to change the shadow offset. Values that are not finite numbers are ignored.

context.shadowBlur = BlurValue

The above method is to set, to change or to return the blur level. Values that are not finite numbers greater than or equal to zero are ignored.

Text in HTML 5 Canvas

context.font = FontValue

The above method is to set, to change or to return the font for the canvas

context.textAlign = AlignValue

The above method is to set, to change or to return the alignment settings for the canvas. The values are start (default), end, left, right, and center.

context.textBaseline = BaselineValue

The above method is to set, to change or to return the Baseline settings for the canvas. The default is alphabetic.

context.fillText(text, x, y [, maxWidth ] )

context.strokeText(text, x, y [, maxWidth ] )

The above methods are to fill or stroke the given text at the given position. If maximum width is included, the text will be scaled to fit that width if needed.

metrics = context.measureText(text)

The above method returns TextMetrics object with the metrics of the given text in the current font.

metrics.width

The above method returns the advance width of the text in the measureText() method.

==========

Below is an example from Mozilla’s developer website:

HTML 5 canvas example from Mozilla -  2D context

canvas example from Mozilla

 <html>
  <head>
   <script type="application/javascript">
 function drawBowtie(ctx, fillStyle) {

   ctx.fillStyle = "rgba(200,200,200,0.3)";
   ctx.fillRect(-30, -30, 60, 60);

   ctx.fillStyle = fillStyle;
   ctx.globalAlpha = 1.0;
   ctx.beginPath();
   ctx.moveTo(25, 25);
   ctx.lineTo(-25, -25);
   ctx.lineTo(25, -25);
   ctx.lineTo(-25, 25);
   ctx.closePath();
   ctx.fill();
 }

 function dot(ctx) {
   ctx.save();
   ctx.fillStyle = "black";
   ctx.fillRect(-2, -2, 4, 4);
   ctx.restore();
 }

 function draw() {
   var canvas = document.getElementById("canvas");
   var ctx = canvas.getContext("2d");

   // note that all other translates are relative to this
   // one
   ctx.translate(45, 45);

   ctx.save();
   //ctx.translate(0, 0); // unnecessary
   drawBowtie(ctx, "red");
   dot(ctx);
   ctx.restore();

   ctx.save();
   ctx.translate(85, 0);
   ctx.rotate(45 * Math.PI / 180);
   drawBowtie(ctx, "green");
   dot(ctx);
   ctx.restore();

   ctx.save();
   ctx.translate(0, 85);
   ctx.rotate(135 * Math.PI / 180);
   drawBowtie(ctx, "blue");
   dot(ctx);
   ctx.restore();

   ctx.save();
   ctx.translate(85, 85);
   ctx.rotate(90 * Math.PI / 180);
   drawBowtie(ctx, "yellow");
   dot(ctx);
   ctx.restore();
 }
    </script>
  </head>
  <body onload="draw()">
    <canvas id="canvas" width="300" height="300"></canvas>
  </body>
 </html>

Incoming search terms:

  • html5 rotate
  • html5 canvas transform
  • html5 canvas rotate
  • html5 ctx
  • html5 rotation
  • html5 canvas blur
  • context translate
  • html5 measureText
  • ctx html5
  • html5 canvas context
Share
Get Adobe Flash player
18 visitors online now
8 guests, 10 bots, 0 members
Max visitors today: 18 at 04:12 am UTC
This month: 141 at 05-02-2012 11:23 am UTC
This year: 141 at 05-02-2012 11:23 am UTC
All time: 141 at 05-02-2012 11:23 am UTC