Submodule 15.1: Canvas HTML element

Site: ΕΛ/ΛΑΚ Moodle
Course: Study / Web Design and Web Development
Book: Submodule 15.1: Canvas HTML element
Printed by: Guest user
Date: Thursday, 25 April 2024, 7:07 AM

Description

  • Text
  • Drawing
  • Image

What is Canvas

The HTML5 canvas element or just canvas is exactly what the name implies—it's a space where you draw (and edit) both images and text.Specifically, with the terms images and text, we mean their representation in terms of a bitmap—the actual pixels that create the image on the screen.

Imagine the canvas as a workspace. Its name, "canvas" reminds us of the painting sheet. However, it would be better to imagine it as the stretcher bars that support the canvas sheet. To actually draw, you need a surface. This surface is the  canvasRenderingContext2D where we actually draw on.

The HTML of a Canvas

It's easy to make a canvas on a Web page:

<canvas id="canvas0"
width="600"
height="400">
</canvas>

If you don't include the width and height, the canvas width and height will be by default 300x150 (Width x Height).

In Canvas you can also add CSS:

<style>
    canvas { border: 1px solid blue;}
</style>

The above CSS rules will create a canvas displayed as:

Empty canvas

CanvasRenderingContext2D

We need CanvasRenderingContext2D to create a surface in which we can draw on.

The steps to use CanvasRenderingContext2D are:

var canvas0 = document.getElementById("mycanvas0");
var context0= canvas.getContext('2d');
/* context0= will be your context */

You only need to do this once and then you can keep using it to do all your drawing.

In the next lesson, we will use this surface to start drawing.

Canvas Text

We will start by learning how to draw text on a canvas.

Some of the most important properties and methods are:

  • font - defines the font properties for the text
  • fillText(text,x,y) - draws "filled" text on the canvas
  • strokeText(text,x,y) - draws text on the canvas (no fill)
  • fillStyle - Sets or returns the color, gradient, or pattern used to fill the drawing

The JavaScript code :

context0.fillStyle = "blue";
context0.font = "3em Calibri";
context0.fillText("My TEXT!", 30, 110); /*use strokeText instead of fillText to see the difference*/

the above, will create a canvas displayed as:

Canvas Text

Canvas drawing

Here we will start actually drawing on our canvas. The first step is to learn how to draw a line.

The JavaScript code that we will need for that is:

/* draw lines between opposite corners to make an X: */
/*Let's set some styles */
context0.strokeStyle = "red";
context0.lineWidth = "2";
/* call beginPath() to start the drawing path*/
context0.beginPath();
/* call moveTo() to position the pen at the starting point at one corner*/
context0.moveTo(0, 0);
/* call lineTo() to define a line to the opposite corner*/
context0.lineTo(context0.canvas.width, context0.canvas.height);
/* call moveTo() to position the pen at the starting point at one corner*/
context0.moveTo(context0.canvas.width, 0);
/* call lineTo() to define a line to the opposite corner*/
context0.lineTo(0, context0.canvas.height);
/* call stroke() to draw it */
context0.stroke();

the above will create two lines that appear as an "X" in our canvas:

Canvas drawing

Canvas image

We can also add and edit images on Canvas.

The JavaScript code to achieve this is:

/*
* We create a Javascript Image object and set its source URL
* to the location of the image file we'll be inserting.
*/
var image0 = new Image();
image0.src = "images/chocolatethings.JPG";
/*
* Here's the handler that loads when the image has finished downloading.
*
* This needs to be asynchronous (triggered by the image load event) since we don't know how
* long the image will take to load.
*/
image0.onload = function(){
    /* draw the image in the canvas window */
    context1.drawImage(image0, 0, 0);
}

the above code will create a canvas displayed as:

Image into Canvas

Exercise

Let's create an HTML file which includes all these:

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Canvas HTML element </title>
      <style>
           canvas { border: 1px solid blue;}
      </style>
  </head>
  <body >
      <h3>Canvas HTML element </h3>
      <canvas id="myCanvas0" height="400" width="600"></canvas>
      <canvas id="myCanvas1" height="400" width="600"></canvas>

      <script>
           /* We'll grab the canvas elements and the graphics contexts here*/
           var canvas0 = document.getElementById("myCanvas0"); /* HTMLCanvasElement */
           var context0 = canvas0.getContext('2d'); /* CanvasRenderingContext2D */
           var canvas1 = document.getElementById("myCanvas1"); /* HTMLCanvasElement */
           var context1 = canvas1.getContext('2d'); /* CanvasRenderingContext2D */

           /* Let's add some text*/
           context0.fillStyle = "blue";
           context0.font = "3em Calibri";
           context0.fillText("My TEXT!", 30, 110); /*use strokeText instead of fillText to see the difference*/

           /* draw lines between opposite corners to make an X: */
           /* Let's set some styles */
           context0.strokeStyle = "red";
           context0.lineWidth = "2";
           /* call beginPath() to start the drawing path*/
           context0.beginPath();
           /* call moveTo() to position the pen at the starting point at one corner*/
           context0.moveTo(0, 0);
           /* call lineTo() to define a line to the opposite corner*/
           context0.lineTo(context0.canvas.width, context0.canvas.height);
           /* call moveTo() to position the pen at the starting point at one corner*/
           context0.moveTo(context0.canvas.width, 0);
           /* call lineTo() to define a line to the opposite corner*/
           context0.lineTo(0, context0.canvas.height);
           /* call stroke() to draw it */
           context0.stroke();            /*
           * We create a Javascript Image object and set its source URL
           * to the location of the image file we'll be inserting.
           */
           var image0 = new Image();
           image0.src = "images/chocolatethings.JPG";
           /* Here's the handler that loads when the image has finished downloading. */
           image0.onload = function(){
                         /* draw the image in the canvas window */
                          context1.drawImage(image0, 0, 0);
           }
      </script>
  </body>
</html>

Tip: Copy the above piece of code and paste it directly into your editor. Save the file as exersice15.1.a.html in the folder "yourNameWEB2JS", to see how it works. Click here to download the image chocolatethings.jpg in the folder "yourNameWEB2JS/images"

For more information: https://www.w3schools.com/graphics/canvas_intro.asp

Exercise

  1. Open the file exersice15.1.a.html in the folder "Exercises" in your editor and save it as.exersice15.1.b.html in the same folder
  2. Add a circle into the first canvas and save the file. The browser's output should be as shown in the following image:

Solution:

/*add a circle*/
context0.beginPath();
context0.arc(300,200,100,0,2*Math.PI);
context0.stroke();