Top Searches Google PlayFishPHPhiQuerysquish\Squishsexissue town᲼᲼᲼᲼᲼TYPESCRIPT

There's been an update to our Terms of Service. Check it out here.

HTML Canvas - Learn: QuerySquish.com

HTML Canvas

In the previous lesson, we learned about HTML attributes. Now, let's learn about the HTML Canvas element and how to use it to draw graphics on a web page.

What is HTML Canvas?

The HTML <canvas> element is used to draw graphics on a web page using JavaScript. It can be used to draw shapes, text, images, and other objects.

Creating a Canvas

Here is a basic example of a canvas element:


    <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
        Your browser does not support the HTML canvas tag.
    </canvas>
    

Drawing on the Canvas

To draw on the canvas, you need to use JavaScript. Here is an example of how to draw a rectangle on the canvas:


    <script>
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(0, 0, 150, 75);
    </script>
    

Example Usage

Let's see how to use the canvas element and draw different shapes:


    <canvas id="exampleCanvas" width="400" height="200" style="border:1px solid #000000;">
        Your browser does not support the HTML canvas tag.
    </canvas>

    <script>
    var canvas = document.getElementById("exampleCanvas");
    var ctx = canvas.getContext("2d");

    // Draw a rectangle
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(20, 20, 150, 100);

    // Draw a circle
    ctx.beginPath();
    ctx.arc(240, 70, 50, 0, 2 * Math.PI);
    ctx.stroke();

    // Draw text
    ctx.font = "30px Arial";
    ctx.fillText("Hello Canvas", 10, 170);
    </script>
    

More JavaScript in-depth JavaScript tutorials can be found here.