Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

HTML5 Canvas Drawing Techniques and API Usage

Tech Jul 19 35

Cenvas Element Basics

The HTML5 canvas element creates a drawing surface for JavaScript rendering:

<canvas id="drawingSurface" width="400" height="400">
  Canvas not supported in your browser
</canvas>

Canvas itself has no drawing capabilities - all rendering occurs through JavaScript API calls.

Browser Compatibility Check

const canvas = document.getElementById('drawingSurface');
if (!canvas.getContext) {
  console.warn('Canvas not supported');
} else {
  console.log('Canvas supported');
}

Drawing Fundametnals

Line Drawing

const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(200, 200);
ctx.strokeStyle = 'blue';
ctx.stroke();

Rectangle Drawing

ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.fillRect(30, 30, 150, 100);

Circle Drawing

ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();
ctx.closePath();

Text Rendering

ctx.font = '24px Arial';
ctx.fillStyle = 'purple';
ctx.fillText('Hello Canvas', 50, 50);

ctx.strokeStyle = 'orange';
ctx.lineWidth = 1;
ctx.strokeText('Outlined Text', 50, 100);

Image Handling

const img = new Image();
img.src = 'example.png';
img.onload = function() {
  ctx.drawImage(img, 0, 0, 200, 200);
};

Shape Construction

// Triangle
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 200);
ctx.lineTo(50, 200);
ctx.closePath();
ctx.stroke();

Transformations

ctx.save();
ctx.translate(100, 100);
ctx.rotate(Math.PI / 4);
ctx.fillRect(0, 0, 50, 50);
ctx.restore();

Practical Exercises

  1. Draw a diagonal line
  2. Create a filled circle
  3. Render a rectangle with border
  4. Display formatted text
  5. Load and position an image
  6. Apply image transformations
Tags: HTML5Canvas

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.