2079 10

BIT251 ยท 2079 ยท 5 marks

What is canvas element? Write a HTML script to create a canvas field having id cv1 and draw a circle inside the canvas.

What is canvas element? Write a HTML script to create a canvas field having id cv1 and draw a circle inside the canvas. [5]

Web Technology IChapter 6: HTML5 Multimedia and CanvasCanvas element and drawing

Quick answer

The <canvas> element is an HTML5 element used to draw graphics on a web page using JavaScript. It acts as a drawing container (a rectangular area/field) on which graphics, shapes, images, animations, and other visual content can be rendered dynamically through scripting (usually JavaScript).

Canvas Element in HTML

What is Canvas Element?

Key Points:

  • It is defined using the <canvas> tag.
  • By default, it has no border and no content.
  • The actual drawing is done using JavaScript with the Canvas API.
  • Common attributes: id, width, height.

Syntax:

<canvas id="myCanvas" width="value" height="value"></canvas>

HTML Script: Canvas with id="cv1" and a Circle

<!DOCTYPE html>
<html>
<head>
    <title>Canvas Circle Example</title>
</head>
<body>

    <h2>Drawing a Circle on Canvas</h2>

    <!-- Canvas field with id cv1 -->
    <canvas id="cv1" width="400" height="300"
            style="border: 2px solid black;">
        Your browser does not support the canvas element.
    </canvas>

    <script>
        // Step 1: Get the canvas element by its id
        var canvas = document.getElementById("cv1");

        // Step 2: Get the 2D drawing context
        var ctx = canvas.getContext("2d");

        // Step 3: Begin drawing the circle
        ctx.beginPath();

        // Step 4: arc(x, y, radius, startAngle, endAngle)
        // x=200, y=150 is the center; radius=80
        // 0 to 2*Math.PI draws a full circle
        ctx.arc(200, 150, 80, 0, 2 * Math.PI);

        // Step 5: Set fill color and fill the circle
        ctx.fillStyle = "skyblue";
        ctx.fill();

        // Step 6: Set stroke (border) color and draw the border
        ctx.strokeStyle = "navy";
        ctx.lineWidth = 3;
        ctx.stroke();
    </script>

</body>
</html>

Explanation of Key Steps

StepCodePurpose
1getElementById("cv1")Selects the canvas element
2getContext("2d")Gets the 2D rendering context
3beginPath()Starts a new drawing path
4arc(x, y, r, 0, 2*Math.PI)Defines a full circle
5fill()Fills the circle with color
6stroke()Draws the circle border

Note: arc(x, y, radius, startAngle, endAngle) - angles are in radians. A full circle = 2 * Math.PI radians (360ยฐ).

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.