Setting Up Canvas in HTML:

 

To begin, let's create a simple HTML document with a Canvas element.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas Example</title>
    <style>
        canvas {
            border: 1px solid black; /* Adding a border for visualization */
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script src="script.js"></script>
</body>
</html>





In this HTML code:
 
  • We have included a <canvas> element with an id of "myCanvas" and specified its width and height attributes.
  • Inside the <head> section, we added a simple CSS style to give the Canvas a black border for visualization purposes.
  • We linked an external JavaScript file named "script.js" using the <script> tag. This is where we will write our JavaScript code to interact with the Canvas.


Accessing Canvas with JavaScript:

 

Now, let's create the "script.js" file and write JavaScript code to access the Canvas element and draw on it.



// Get the Canvas element using its ID
const canvas = document.getElementById('myCanvas');

// Check if the browser supports Canvas
if (canvas.getContext) {
    // Get the 2D rendering context
    const ctx = canvas.getContext('2d');

    // Set drawing properties (e.g., fill color, line style)
    ctx.fillStyle = 'blue'; // Set fill color to blue
    ctx.fillRect(50, 50, 100, 100); // Draw a blue rectangle at (50, 50) with width 100 and height 100
} else {
    // Display a message if Canvas is not supported
    alert('Canvas is not supported in this browser.');
}
 





In this JavaScript code:

 
  • We first check if the browser supports the <canvas> element using canvas.getContext. If supported, we proceed with drawing on the Canvas.
  • We get the 2D rendering context of the Canvas using canvas.getContext('2d'). This context (ctx) is where we perform all drawing operations.
  • We set the fill color to blue using ctx.fillStyle and then draw a blue rectangle on the Canvas using ctx.fillRect.


Explanation:
 
  • Canvas Element: The <canvas> element provides a drawing surface in HTML for rendering graphics dynamically.
  • JavaScript Access: We use JavaScript to access the Canvas element by its ID (getElementById) and obtain the 2D rendering context (getContext('2d')).
  • Drawing Operations: With the rendering context, we can set drawing properties (e.g., fill color, stroke style) and perform drawing operations (e.g., fillRect for rectangles).
  • Browser Support: We include a check to ensure that the browser supports Canvas before attempting to draw on it.


Advantages of Canvas:
  • Ideal for dynamic graphics, animations, games, and data visualizations.
  • Offers pixel-level control and rendering capabilities.
  • Supports complex rendering operations like paths, gradients, and transformations.

 



Practice Excercise Practice now