Apps

HTML5: Drawing images and adding text to the canvas element

Ryan Boudreaux shows more examples of working with the canvas element in HTML5, this time drawing images and adding text with the various functions available.

In the previous post, "HTML5: Working with the canvas element," I reviewed several ways to manipulate this element, including creating rectangles, circles, triangles, and diamond shapes by drawing paths, and with various shades using rgba. In this segment we will review drawing images and playing around with adding text to the canvas.

The canvas drawImage function using JavaScript allows you to create an image object within the defined canvas area. The drawImage function includes three parameters and is expressed in the form drawImage(object image, float x, float y). The image file formats supported within the canvas element and drawImage function are .jpg, .gif, and .png. For the draw image function to work, we have to set the variable and define the image object. For this example, we set it to "img" as is expressed in var img = new Image(); and then the image source is provided, followed by the image onload, and the final drawImage function with the parameters defined as in the example below:
// Draw Image function
var img = new Image();
img.src = "images/Figure_A.png";
img.onload = function() {
context.drawImage(img, 145, 145);
};

The resulting canvas image is displayed below as shown in Firefox 3.6:

Figure A

The entire code snippet is displayed here:

<body onLoad="drawCanvas();">
<!-- Script draw canvas circle and draw image -->
<script>
function drawCanvas() {
var circle_canvas = document.getElementById("canvas");
var context = circle_canvas.getContext("2d");
// Fill Style
context.fillStyle = "rgba(93,179,199,0.20)";
// Begin path
context.beginPath();
//Canvas shape
context.arc(225,225,115,0,Math.PI*2,true);
// Close path
context.closePath();
// Fill shape
context.fill();
// Draw Image function
var img = new Image();
img.src = "images/Figure_A.png";
img.onload = function() {
context.drawImage(img, 145, 145);
      };
}
</script>
    <h1>Canvas Examples</h1>
    <h2>Draw image function example</h2>
    <!-- canvas circle element tag -->
    <canvas id="canvas" width="340" height="340">
       <!-- Fallback content -->
       <p>We apologize, your browser does not support canvas at this time!</p>
    </canvas>

Adding text

Canvas text can be drawn using font and text attributes along with several text methods. The font attribute string has a default setting of 10px, sans-serif, and can include anything that you would normally add within a CSS font rule. The textAlign attribute string is self explanatory, and it has a default value of start and supports the values: start, end, left, right, or center. The textBaseline IDL attribute string has a default of alphabetic, and supports the values: top, hanging, middle, alphabetic, ideographic, or bottom.

The WHATWG specifies the textBaseline attribute's keywords which correspond to the alignment points in the font, where:
  • top corresponds to the top of the em square
  • hanging is the hanging baseline
  • middle is the middle of the em square
  • alphabetic is the alphabetic baseline
  • ideographic is the ideographic baseline
  • bottom corresponds to the bottom of the em square

The text methods include:

  • fillText(string text, float x, float y, [optional] float maxWidth)
  • strokeText(string text, float x, float y, [optional] float maxWidth)

Metrics interface include measureText(string text) and returns a TextMetrics object of the given text in the current font, i.e., metrics = context.measureText(string text).

A basic text example includes context for the thickness of the stroke using lineWidth, and color of the fill is set using the fillStyle which can also be used to establish gradient settings; the color of the stroke is set using the lineStyle; font and fillText are also shown below in the JavaScript code and HTML snippets.
<script>
function drawCanvas() {
  var canvas = document.getElementById("canvasText");
  var context = canvas.getContext('2d');
 // Fill Text
context.lineWidth=1;
context.fillStyle="#CC00FF";
context.lineStyle="#ffff00";
context.font="18px sans-serif";
context.fillText("Fill Text, 18px, sans-serif", 20, 20);
}
</script>
 <h2>Canvas text examples</h2>
 <!-- canvas element tag -->
   <canvas id="canvasText" width="235" height="25">
     <!-- Fallback content -->
      <p>We apologize, your browser does not support canvas at this time!</p>
    </canvas>

The screenshot below shows the result of the above code as displayed in Firefox 3.6.

Figure B

The next example shows strokeText using JavaScript code with the resulting screenshot below.

<script>
function drawCanvas() {
  var canvas = document.getElementById("canvasText");
  var context = canvas.getContext('2d');
// Stroke Text
  context.font="22px verdana";
  context.strokeText("Stroke Text, 22px, veranda", 20, 50);
}
</script>

Figure C

Font play in this example shows adding italics, 26px, and times to the font:

<script>
function drawCanvas() {
  var canvas = document.getElementById("canvasText");
  var context = canvas.getContext('2d');
// Italic Stroke Text
  context.font="italic 26px Times";
  context.strokeText("Italic, Stroke, Text, 26px, times", 20, 85);
}
</script>

Figure D

Fill Stroke Text, in this example, demonstrates context for both the fillText and the strokeText, which means that the text must be drawn twice with the same x and y coordinates, as displayed in the JavaScript snippet and accompanying screenshot:
<script>
function drawCanvas() {
  var canvas = document.getElementById("canvasText");
  var context = canvas.getContext('2d');
// Fill Stroke Text
  context.lineWidth=2;
  context.strokeStyle="rgba(35, 70, 237, .8)";
  context.font="28pt sans-serif";
  context.fillText("Fill, Stroke Text, 28pt, sans-serif", 20, 130);
  context.strokeText("Fill, Stroke Text, 28pt, sans-serif", 20, 130);
}
</script>

Figure E

Shadow text effects can be rendered in canvas utilizing context for shadowOffsetX, shadowOffsetY, and shadowColor as shown in the example snippet and accompanying screenshot:

<script>
function drawCanvas() {
  var canvas = document.getElementById("canvasText");
  var context = canvas.getContext('2d');
//Shadow Bold Text
context.lineWidth=1;
context.fillStyle="#0000ff";
context.strokeStyle="#880000";
context.font="bold 28pt sans-serif";
context.shadowOffsetX=2;
context.shadowOffsetY=-2;
context.shadowColor="#888888";
context.fillText("Shadow, Bold Text, 28pt, sans-serif", 20, 180);
}
</script>

Figure F

Blur is added with the context shadowBlur; the JavaScript code snippet and resulting screenshot are below:

<script>
function drawCanvas() {
  var canvas = document.getElementById("canvasText");
  var context = canvas.getContext('2d');
//Shadow Blur Stroke Bold Text
context.fillStyle="#5CADE9";
context.lineStyle="#5CADE9";
context.font="bold 28pt sans-serif";
context.shadowOffsetX=4;
context.shadowOffsetY=4;
context.shadowBlur=8;
context.fillText("Shadow, Blur, Stroke, Bold Text, 28pt", 20, 220);
context.strokeText("Shadow, Blur, Stroke, Bold Text, 28pt", 20, 220);
}
</script>

Figure G

Gradient text is created using the variable to create a linear gradient with two pairs of coordinates in the form createLinearGradient(x1, y1, x2, y2), where the variable is set as var gradient=context.createLinearGradient(5, 50, 500, 20); in this example. It can be drawn when set as a fillStyle. In the example below, we utilize combinations of both fill and stroke text with the gradient settings:
<script>
function drawCanvas() {
  var canvas = document.getElementById("canvasText");
  var context = canvas.getContext('2d');
// Gradient Text Fill and Stroke
  var gradient=context.createLinearGradient(5, 50, 500, 20);
  gradient.addColorStop(0.1, '#F82E23');
  gradient.addColorStop(0.25, '#E2E651');
  gradient.addColorStop(0.5, '#55D268');
  gradient.addColorStop(0.75, '#5A77DA');
  gradient.addColorStop(1, '#C84489');
  context.fillStyle=gradient;
  context.font="bold 36pt sans-serif";
  context.shadowOffsetX=5;
  context.shadowOffsetY=5;
  context.shadowBlur=10;
  context.fillText("Gradient Fill Text", 20, 280);
  context.fillStyle='#000000';
  context.strokeStyle=gradient;
  context.lineWidth=3;
  context.strokeText("Gradient Stroke Text", 20, 350);
}
</script>

Figure H

Other ways of representing canvas text can include on a path using the context mozTextAlongPath function to draw text on circles, lines, or shapes. Image patterns can also be incorporated into text using the fillStyle method with the createPattern(img, repeat) function.

About

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal g...

0 comments

Editor's Picks