Drawing rectangles – immediate drawing mode

EXAMPLE: DRAWING RECTANGLES IN IMMEDIATE MODE USING GOOD PRACTICE

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Some rectangles drawn in immediate mode</title>
  5. <style>
  6.     #myCanvas {
  7.         border: 1px solid #9C9898;
  8.     }
  9. </style>
  10.     var canvas, ctx;
  11.  
  12.     window.onload = function () {
  13.        canvas = document.getElementById(‘myCanvas’);
  14.        ctx = canvas.getContext(‘2d’);
  15.  
  16.        // black rectangle, default color (black)
  17.        ctx.fillRect(10, 10, 100, 100);
  18.        // outlined rectangle, default color
  19.        ctx.strokeRect(150, 10, 100, 100);
  20.  
  21.        // outlined rectangle filled in red, outline blue
  22.        ctx.fillStyle = ‘red’;
  23.        ctx.strokeStyle = ‘lightBlue’;
  24.        ctx.lineWidth = 10;
  25.        ctx.fillRect(100, 150, 150, 150);
  26.        ctx.strokeRect(100, 150, 150, 150);
  27.  
  28.        // A function that automatizes previous drawing
  29.        var angle = Math.PI / 10;
  30.        drawFilledRectangle(300, 150, 150, 150, ‘pink’, ‘green’, 10, angle);
  31.        drawFilledRectangle(300, 150, 150, 150, ‘yellow’, ‘purple’, 10, angle +0.5);
  32. };
  33.  
  34. function drawFilledRectangle(x, y, w, h, fillColor, strokeColor, lw, angle) {
  35.     // GOOD PRACTICE: save if the function changes the context
  36.     // or coordinate
  37.     // system
  38.     ctx.save();
  39.  
  40.     // position coordinate system
  41.     ctx.translate(x, y);
  42.     ctx.rotate(angle);
  43.  
  44.     // set colors, line width…
  45.     ctx.lineWidth = lw;
  46.     ctx.fillStyle = fillColor;
  47.     ctx.strokeStyle = strokeColor;
  48.  
  49.     // draw at 0, 0 as we translated the coordinate
  50.     // system already
  51.    ctx.fillRect(0, 0, w, h);
  52.    ctx.strokeRect(0, 0, w, h);
  53.  
  54.    // GOOD PRACTICE: a restore for a save!
  55.    ctx.restore();
  56. }
  57. </head>
  58. <body>
  59.      <canvas id=“myCanvas” width=“578” height=“400”>
  60.      </canvas>
  61. </body>
  62. </html>

Drawing text

INTRODUCTION

The canvas API provides two main methods for drawing text: ctx.strokeText(message, x, y) and ctx.fillText(message, x, y).

  1. context.font = “60pt Calibri”;
  2. // .. set color, lineWidth, shadow etc.
  3. // 10, 10 is the start of the baseline, bottom of left leg of the “H” in the
  4. // “Hello World” example.
  5. context.fillText(“Hello World!”, 10, 10);
  6. // Or
  7. context.strokeText(“Hello World!”, 10, 10);

THE CONTEXT.FONT PROPERTY:

The font property is CSS-compliant, and accepts values like:

[font style][font weight][font size][font face]

Accepted values are:

    • font style: normal, italic, oblique, inherit
    • font weight: normal, bold, bolder, lighter, auto, inherit, 100, 200, 300, 400, 500, 600, 700, 800, 900
    • font size: a size in pixels or in points, such as 60pt, 20px, 36px, etc.
    • font face: Arial, Calibri, Times, Courier, etc. Some font faces may not work in all browsers.

Examples:

    • context.font = “60pt Calibri”;
    • context.font = “normal normal 20px Verdana”;
    • context.font = “normal 36px Arial”;
    • context.font = “italic bold 36px Arial”;

THE FILLTEXT() OR STROKETEXT() METHODS

The fillText(message, x, y) or strokeText(message, x, y) methods from the context will actually draw a text message at the origin of the baseline position. In the “Hello World” example, this is located at the bottom of the left leg of the “H”.

There is a fourth optional parameter maxWidth that forces the text to fit into a given width, distorting it if necessary:

  1. context.strokeText(“Hello World!”, x, y [, maxWidth]);
  2. context.fillText(“Hello World!”, x, y [, maxWidth]);

EXAMPLE THAT USES THE MAXWIDTH  PARAMETER OF THE STROKETEXT() OR FILLTEXT() METHODS:

Try it online: http://jsbin.com/zixeve/2/edit

  1. context.font = “60pt Calibri”;
  2. context.lineWidth = 3;
  3. context.strokeStyle = “blue”;
  4. context.fillStyle = “red”;
  5. context.fillText(“Hello World!”, 10, 100);
  6. context.strokeText(“Hello World!”, 10, 100);
  7. // Draw text with constrained width of 250 pixels
  8. context.fillText(“Hello World!”, 10, 160, 250);
  9. context.strokeText(“Hello World!”, 10, 160, 250);
  10. // Constrain width to 150 pixels
  11. context.fillText(“Hello World!”, 10, 220, 150);
  12. context.strokeText(“Hello World!”, 10, 220, 150);

MEASURING THE WIDTH OF A GIVEN TEXT (BOUNDING BOX)

The ctx.measureText() method can be used to get the current width in pixels of a given text, taking into account the diverse properties involved such as font, size, shadow, lineWidth, etc.

Source code extract from this example:

  1. context.font = “60pt Calibri”;
  2. context.lineWidth = 3;
  3. context.strokeStyle = “blue”;
  4. context.fillStyle = “red”;
  5. context.fillText(“Hello World!”, 10, 100);
  6. context.strokeText(“Hello World!”, 10, 100);
  7. var textMetrics = context.measureText(“Hello World!”);
  8. var width = textMetrics.width;
  9. // Draw a text that displays the width of the previous drawn text
  10. context.font = “20pt Arial”;
  11. context.fillText(“Width of previous text: “ + width + “pixels”, 10, 150);
  12. // Draw the baseline of the given width
  13. context.moveTo(10, 100);
  14. context.lineTo(width+10, 100);
  15. context.stroke();

THE CTX.TEXTBASELINE PROPERTY: CHANGE THE WAY THE TEXT IS HORIZONTALLY DRAWN

Try this example at JS Bin

The text baseline is important as it tells how the y parameter of the fillText(“some text”, x, y) and strokeText(“some text”, x, y) methods is interpreted.

Possible values:

Possible values for the textBaseline property
top The text is aligned based on the top of the tallest glyph in the text.
hanging The text is aligned based on the line the text seems to hang from. This is almost identical to top, and in many cases, you cannot see the difference.
middle The text is aligned according to the middle of the text.
alphabetic The bottom of vertically oriented glyphs, e.g. western alphabet like the latin.
ideographic The bottom of horizontally oriented glyphs.
bottom The text is aligned based on the bottom of the glyph in the text, that extends furthest down in the text.

Typical use (taken from the example above):

  1. context.textBaseline = “top”;
  2. context.fillText(“top”, 0, 75);
  3. context.textBaseline = “hanging”;
  4. context.fillText(“hanging”, 40, 75);
  5. context.textBaseline = “middle”;
  6. context.fillText(“middle”, 120, 75);

HORIZONTAL TEXT ALIGNMENT

Try this example online: http://jsbin.com/acudif/3/edit

The textAlign property of the context tells how the x parameter will be used when calling strokeText(“some text”, x, y) and fillText(“some text”, x, y). For example, with textAlign=”center”, the x parameter gives the position of the vertical center of the text, while in textAlign=”right”, x corresponds to the rightmost position of the text.

Typical use (source code taken from the above example):

  1. context.textAlign = “center”;
  2. context.fillText(“center”, 250, 20);
  3. context.textAlign = “start”;
  4. context.fillText(“start”, 250, 40);
  5. context.textAlign = “end”;
  6. context.fillText(“end”, 250, 60);
  7. context.textAlign = “left”;
  8. context.fillText(“left”, 250, 80);
  9. context.textAlign = “right”;
  10. context.fillText(“right”, 250, 100);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s