Html Course


About HTML5 Canvas

The <canvas> tag is one of the most interesting HTML5 features.
The <canvas> element itself is quite simple, defining the width, height, and unique ID for the object. The developer must then use a series of JavaScript APIs to draw objects on the canvas.
The example below shows the basic structure of implementing the canvas:

<canvas id='id_canvas' width='200' height='200'></canvas>

<script>
function draw() {
 // get a reference to the <canvas> tag
 var canvas = document.getElementById('id_canvas');

 // if the browser support canvas
 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');
 // Apply JavaScript APIs for drawing
 }
}

// calls the draw() function
draw();
</script>
- width and height attributes specify the size of the CANVAS space on the screen.
- It is the ID that is important (here the ID is 'id_canvas'), you use it in JavaScript to get a reference to the <canvas> (with document.getElementById('ID')), then you can apply specific functions and properties to create drawings that will appear in the CANVAS tag.
- The getContext('2d') method must be applied to the canvas element, to get an object at which will be applied API instructions to create the context in <canvas>.

<canvas> is a block type element, can be added within any other block tag, like <p>, <div>, or into the new structure elements introduced in HTML5: <section>, <article>.


Drawing with HTML5, canvas and JavaScript

The JavaScript APIs allow the developer to draw shapes and lines; apply color, opacity, and gradients; create text; transform canvas objects; and perform animation.
- The example below draws a blue box.

<h4>Example drawing square in canvas</h4>

<canvas width='200' height='200' id='cav1'></canvas>

<script>
function draw() {
 var canvas = document.getElementById('cav1');

 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');
 ctx.fillStyle = '#0101fe';
 ctx.fillRect (50, 60, 100, 100);
 }
}

draw(); // calls the draw() function
</script>
- Syntax:

Adding transparency

To add transparency, define the color using the rgba(Red, Green, Blue, Opacity) format. Opacity is a value between 0 and 1 that represents the transparency.
Let's introduce another box, but with opacity of 50%. In this case we define fillStyle for the second shape, using rgba() to specify an alpha (or opacity) value along with the color ( 'rgba(220, 223, 0, 0.5)' ).

<h4>Example canvas opacity</h4>

<canvas width='200' height='200' id='cav1'></canvas>

<script>
function draw() {
 var canvas = document.getElementById('cav1');

 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');
 ctx.fillStyle = '#0101fe';
 ctx.fillRect (50, 60, 100, 100);
 ctx.fillStyle = 'rgba(220,223,0, 0.5)';
 ctx.fillRect (90, 105, 100, 80);
 }
}

draw(); // calls the draw() function
</script>

Drawing lines

To draw lines, use the lineTo() function.
lineTo(x, y)
This method define a line from the starting current point till the coordinates (x, y).
To set or move the starting point for drawing, use the moveTo() method.
moveTo(x, y)
- This method creates a new subpath (a starting point) with the given point.

To define a color for the line, use: ctx.strokeStyle = 'color';
To define the thickness of the line (in pixels), use: ctx.lineWidth = value;

The following code creates three lines.

After we define the color of the line (with strokeStyle), and the thickness (with lineWidth), we use the moveTo() method to set the start point, then withU lineTo(100, 80) we draw a line till the (100, 80) point coordinate.
Now, the last point becomes the current starting point, to move it, we use again the moveTo() method.

<h4>Example canvas drawing lines</h4>

<canvas width='200' height='200' id='cav1'></canvas>

<script>
function draw() {
 var canvas = document.getElementById('cav1');

 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');

 // define line color and width
 ctx.strokeStyle = '#01da01';
 ctx.lineWidth = 3;

 // create the first line
 ctx.moveTo(10, 10); // sets the start point
 ctx.lineTo(100, 80); // define a line till these coordinates

 // create the second line
 ctx.moveTo(10, 10); // sets the start point
 ctx.lineTo(120, 120); // define a line till these coordinates

 // the third line
 ctx.moveTo(10, 150); // moves start point
 ctx.lineTo(140, 150);

 ctx.stroke(); // draw the strokes
 }
}

draw(); // calls the draw() function
</script>

Drawing arcs and circles

To draw arcs and circles, we use the arc() function.
Syntax:
arc(x, y, radius, startAngle, endAngle, anticlockwise)
- This method draws an arc between the startAngle and endAngle, going anti-clockwise if the anticlockwise argument is true, and clockwise otherwise.
To draw a circle, set startAngle=0, endAngle=Math.pi*2

After you define the arc (or circle) with the arc() method, apply:
    ctx.stroke();   - to draw the margin /border.
    ctx.fill();   - to add the fill color.

The next example draws a smiling face.
<h4>Example canvas arcs and circles</h4>

<canvas width='200' height='200' id='cav1'></canvas>

<script>
function draw() {
 var canvas = document.getElementById('cav1');

 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');
 ctx.arc(75,75,50,0,Math.PI*2,true); // Face
 ctx.moveTo(110,75);
 ctx.arc(75,75,35,0,Math.PI,false); // Mouth
 ctx.moveTo(65,65);
 ctx.arc(60,65,4,0,Math.PI*2,true); // Left eye
 ctx.moveTo(95,65);
 ctx.arc(90,65,4,0,Math.PI*2,true); // Right eye
 ctx.stroke();
 }
}

draw();
</script>

Canvas - Text

You have two methods for drawing text in canvas:
The following text properties are available on the context object:
Example:
<h4>Example text in canvas</h4>

<canvas width='200' height='200' id='cav1'></canvas>

<script>
function draw() {
 var canvas = document.getElementById('cav1');

 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');

 // create text with fill color
 ctx.fillStyle = '#00f';
 ctx.font = 'italic 30px sans-serif';
 ctx.textBaseline = 'top';
 ctx.fillText('Hy everyone', 2, 5);

 // create text without fill color
 ctx.font = 'bold 30px sans-serif';
 ctx.strokeText('Hy everyone', 2, 50);
 }
}

draw();
</script>

Canvas - Shadows

The Shadow API gives you four properties that are applied to context object:
The next code draws a blue sphere with a yellow shadow having 50% transparency:
<h4>Example canvas - shadow</h4>

<canvas width='200' height='200' id='cav1'></canvas>

<script>
function draw() {
 var canvas = document.getElementById('cav1');

 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');

 // sets shadow properties
 ctx.shadowOffsetX = 8;
 ctx.shadowOffsetY = 8;
 ctx.shadowBlur = 4;
 ctx.shadowColor = 'rgba(200, 200, 1, 0.5)';

 // define and add a circle
 ctx.fillStyle = '#0000fe';
 ctx.arc(75,75,50,0,Math.PI*2,true);
 ctx.fill();
 }
}

draw();
</script>

Canvas - Gradient

To create gradients in Canvas, you assign a CanvasGradient object to the fillStyle and strokeStyle properties.
You can create two types of CanvasGradient object, using one of the following methods:


Once you have the gradient object you can add color stops along the gradient using the addColorStop() method of the object. The following two codes shows you how to use gradients.
  1) Example with createLinearGradient():
<h4>Example canvas - Gradient</h4>

<canvas width='200' height='200' id='cav1'></canvas>

<script>
function draw() {
 var canvas = document.getElementById('cav1');

 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');

 // create a Linear CanvasGradient object
 // provide the source, the start and end (x0, y0, x1, y1) coordinates
 var gradient = ctx.createLinearGradient(0, 0, 150, 0);

 // Now add colors in your gradient, the first argument tells the position for the color
 // - accepted value range is from 0 (gradient start) to 1 (gradient end)
 // The second argument tells the color you want, using the CSS color format
 gradient.addColorStop(0, '#f00'); // red
 gradient.addColorStop(0.4, '#ff0'); // yellow
 gradient.addColorStop(0.8, '#0f0'); // green
 gradient.addColorStop(1, '#00f'); // blue
 

 // Apply the gradient to fillStyle property, and draw an rectangle
 ctx.fillStyle = gradient;
 ctx.fillRect(0, 0, 200, 125);
 }
}

draw();
</script>
  2) Example with createRadialGradient():
<h4>Example canvas - Gradient with createRadialGradient()</h4>

<canvas width='200' height='200' id='cav1'></canvas>

<script>
function draw() {
 var canvas = document.getElementById('cav1');

 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');

 // create a Radial CanvasGradient object
 // provide the source, the start, end and radius (x0, y0, r0, x1, y1, r1) of the circles
 var gradient = ctx.createRadialGradient(70, 80, 10, 78, 75, 45);

 // Adding colors to a radial gradient is the same as adding colors to linear
 gradient.addColorStop(0, '#0f0');
 gradient.addColorStop(0.5, '#fff');
 gradient.addColorStop(1, '#00f');
 

 // Apply the gradient to fillStyle property, and draw an circle
 ctx.fillStyle = gradient;
 ctx.arc(75,75,50,0,Math.PI*2,true);
 ctx.fill();
 }
}

draw();
</script>

HTML5 Canvas - Inserting images

To insert images in a <canvas>, use the drawImage() method. It is a complex method that uses three, five, or nine arguments.
Here's the syntax with five arguments:

drawImage(img_element, dx, dy, dw, dh)
- The first argument, img_element represents the reference to an image, 'dx' and 'dy' specify the destination coordinates inside your canvas context, 'dw' and 'dh' specify the width and height of the inserted image (in cases where you want to resize it).
- The variant with nine arguments can be used to crop the image, it adds four more arguments that set the coordinates (x0, y0, x1, y1) for the crop area.

In the following example we insert this image: HTML5 course in a <canvas> (resizing it), and a text next to it.
<h4>Example canvas - shadow</h4>

<canvas width='280' height='200' id='cav1'></canvas>

<script>
function draw() {
 var canvas = document.getElementById('cav1');

 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');

 // create an object with the image, then adds it in canvas context (resizing it)
 var img = new Image();
 img.src ='html/html_course.jpg';
 ctx.drawImage(img, 0, 0, 95, 100);

 // add a text without fill color
 ctx.font = 'bold 25px sans-serif';
 ctx.textBaseline = 'top';
 ctx.strokeText('HTML Course', 100, 38);
 }
}

draw();
</script>
• The JavaScript APIs also allow the <canvas> to be interactive and respond to user input such as mouse events and key events, facilitating the production of games and Web applications on the canvas.
- In the next example we use 'mouseenter', 'mouseleave', and 'click' events, to change the color of a rectange in <canvas>.

The "fillStyle" property uses the color passed in parameter, so when we call the draw() function with differen color in argument, the color of the rectangle changes.

<h4>Example canvas - events</h4>
<p>To see the effect, move the mouse over the rectangle below, then click on it.</p>

<canvas width='125' height='85' id='cav1'></canvas>

<script>
var canvas = document.getElementById('cav1');

//receives the color
function draw(clr){
 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');

 // draw a rectangle, using a fill color defined in 'clr' parameter
 ctx.fillStyle = clr;
 ctx.fillRect (0, 0, 120, 80);
 }
}

draw('#0102fe');

//register events that call draw() with desired color
canvas.addEventListener('mouseenter', (ev)=>{
 draw('#fefe01');
});
canvas.addEventListener('mouseleave', (ev)=>{
 draw('#01de02');
});
canvas.addEventListener('click', (ev)=>{
 draw('#fe0708');
});
</script>
There are many other JavaScript properties and methods for Canvas. For a complete documentation about canvas, see the HTML Canvas 2D Context.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
HTML5 Canvas Tutorial

Last accessed pages

  1. Display data from PHP Array, or MySQL in HTML table (26988)
  2. PHP Simple HTML DOM Parser (12469)
  3. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142527)
  4. Paragraphs, Line break, Horizontal rule (4310)
  5. Convert BBCode to HTML and HTML to BBCode with JavaScript (9417)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (530)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)