Lesson 09-Application of HTML5 Canvas Graphics Drawing Technology

Canvas Basics

Creating a Canvas Element
Insert a <canvas> element into your HTML document and assign it an ID so that it can be accessed via JavaScript:

<canvas id="myCanvas" width="500" height="300"></canvas>

This sets the initial width and height of the canvas.

Getting the Canvas Context
Use JavaScript to get the rendering context of the <canvas> element, which is usually a 2D drawing environment:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

The ctx variable now contains all the drawing methods and properties for operating on the canvas.

Basic drawing operations

Draw a straight line
Use beginPath() to start a new path, moveTo() to set the starting point, lineTo() to add a straight line segment, and finally stroke() or fill() to complete the drawing:

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 90);
ctx.stroke();

Draw a rectangle
Use rect() to directly define a rectangle, and then call stroke() or fill() in the same way:

ctx.beginPath();
ctx.rect(10, 10, ¾0, 50);
ctx.fill();

Draw an arc/circle
Use the arc() method to draw an arc or a complete circle:

// Draw an arc
ctx.beginPath();
ctx.arc(75, 75, 50, 0, Math.PI * 2, false); // The parameters are: center point x, y, radius, start arc, end arc, whether counterclockwise
ctx.stroke();

// Draw a circle (fill)
ctx.beginPath();
ctx.arc(1.jpg, 100, 40, 0, Math.PI * 2, false);
ctx.fill();

Fill and stroke
fillStyle and strokeStyle attributes set fill and stroke colors:

ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; // Translucent red fill
ctx.strokeStyle = '#00FF00'; // Green stroke

fill() and stroke() methods are used to fill paths and draw strokes, respectively.

Path Operations

Path Combination
Calling moveTo() and lineTo() multiple times can draw complex paths. All path segments will be processed together when stroke() or fill():

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(150, 90);
ctx.lineTo(50, 90);
ctx.closePath(); // Optional, automatically close the path
ctx.stroke();

Path Filling Rule
The fillRule property controls the algorithm for path filling. The optional values ​​are 'nonzero' (default) and 'evenodd'.

Text drawing

Use fillText() or strokeText() method to draw text on the canvas:

ctx.font = '30px Arial';
ctx.fillText('Hello, Canvas!', 50, 100);

You can set textAlign (alignment), textBaseline (baseline position) and other properties to adjust the text layout.

Image drawing

Load external images and draw them on the canvas:

const img = new Image();
img.src = 'image.png';
img.onload = function() {
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
};

The drawImage() method accepts multiple parameters and can scale, crop or translate the image.

Transformation

Translate

ctx.translate(x, y);

Rotate

ctx.rotate(angleInRadians);

Scale

ctx.scale(xScale, yScale);

Transformations are usually set before drawing, and drawing states can be saved and restored via the save() and restore() methods.

Composite graphics and clipping

clip()

Create a clipping area based on the current path, and subsequent drawing is only visible in this area:

ctx.beginPath();
ctx.rect(10, 10, ¼0, 50);
ctx.clip();
createPattern()

Create a pattern fill to fill the graphics:

const pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);

Shadow

Set the graphic shadow:

ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;
ctx.shadowBlur = 10; 

Gradient Linear Gradient (createLinearGradient)

const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0); 
gradient.addColorStop(0, 'red'); 
gradient.addColorStop(1, 'blue'); 
ctx.fillStyle = gradient; 
ctx.fillRect(0, 0, canvas.width, canvas.height); 
Radial Gradient (createRadialGradient) 

const gradient = ctx.createRadialGradient(75, 75, 50, 90, 60, 100); 
gradient.addColorStop(0, 'red'); 
gradient.addColorStop(1, 'white'); ctx.fillStyle = gradient; 
ctx.fillRect(0, 0, canvas.width, canvas.height);

Animation and Interaction

Use requestAnimationFrame() to implement animation loops and listen for mouse/touch events for interaction:

function drawFrame() {
    // Clear the canvas or redraw the background
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Update the graphics state or position
    // ...

    // Draw a new frame
    // ...

    requestAnimationFrame(drawFrame);
}

drawFrame();

canvas.addEventListener('click', function(event) {
    const mousePos = getMousePos(canvas, event);
    // Respond to click events, such as changing graphics state or displaying prompts
});

Advanced Techniques

  • Use getImageData() and putImageData() for pixel-level operations.
  • Use Web Workers for off-screen rendering or computationally intensive tasks.
  • Combine with WebGL to achieve 3D drawing or high-performance graphics rendering.
Share your love