How to Use Canvas with JavaScript?

Let’s check how to use Canvas with Javascript.

javascript canvas

Canvas is and element introduced into the HTML5. It allows you to dynamically, using JavaScript code, draw shapes and modify images. Thanks to the canvas you can even animate without having to install for additional plugins.

Adding a canvas element to our project is trivial and it is done by simply adding an HTML tag to the page structure:

<canvas id="canvas"></canvas>

Next create a function and draw two rectangles:

    function draw() {
        const canvas = document.getElementById("canvas");
        let myCanvas = canvas.getContext("2d");

        myCanvas.fillStyle = "rgb(0,0,100)";
        myCanvas.fillRect (10, 10, 90, 90);
         
        myCanvas.fillStyle = "rgba(800, 0, 0, 0.6)";
        myCanvas.fillRect (20, 20, 90, 90);
    }

Let’s trigger the fuction:

<canvas id="canvas" width="250" height="250"></canvas>

The whole code:

<html lang="en">
<head>
<meta charset="utf-8">

<script type="application/javascript">
function draw() {
const canvas = document.getElementById("canvas");
let myCanvas = canvas.getContext("2d");

myCanvas.fillStyle = "rgb(0,0,100)";
myCanvas.fillRect (10, 10, 90, 90);

myCanvas.fillStyle = "rgba(800, 0, 0, 0.6)";
myCanvas.fillRect (20, 20, 90, 90);
}

</script>
</head>

<body onload="draw()">
<canvas id="canvas" width="250" height="250"></canvas>
</body>

</html>

Leave a Reply

Your email address will not be published. Required fields are marked *