HTML Canvas

The canvas element of HTML is used for drawing graphics on a webpage.

The <canvas> tag is used to draw canvas in HTML. The <canvas> element is basically a container that is used with script, such as javascript to draw graphics.

We will use Javascript with HTML canvas element to demonstrate example here.

Draw Text with Canvas ands Javascript

Example
Code

<canvas id="canvasText" height="100px" width="auto"></canvas>
<script>
var canvas = document.getElementById("canvasText");
var ctx = canvasText.getContext("2d");
ctx.font = "50px Arial";
ctx.strokeText("Hello HTML", 0, 60);
ctx.strokeStyle = "#dc143c";
</script> 

Draw a circle with Canvas and Javascript

Example
Code

<canvas id="canvasCircle" height="220px" width="auto"></canvas>
<script>
    var canvasCircle = document.getElementById("canvasCircle");
    var ctx2 = canvasCircle.getContext("2d");
    var centerX = canvasCircle.width / 2;
    var centerY = canvasCircle.height / 2;
    var radius = 80;
    ctx2.beginPath();
    ctx2.arc(
        centerX,
        centerY,
        radius,
        0,
        2 * Math.PI,
        false
    );
    ctx2.fillStyle = "blue";
    ctx2.fill();
    ctx2.lineWidth = 4;
    ctx2.strokeStyle = "skyblue";
    ctx2.stroke();
</script>

Draw a smiley with Canvas and Javascript

Example
Code

<canvas id="canvasSmiley" height="220px" width="auto"></canvas>
<script>
    var canvasSmiley = document.getElementById("canvasSmiley");
    var ctx3 = canvasSmiley.getContext("2d");
    ctx3.beginPath();
    ctx3.arc(75, 75, 50, 0, Math.PI * 2, true); // Outer circle
    ctx3.moveTo(110, 75);
    ctx3.arc(75, 75, 35, 0, Math.PI, false); // Mouth (clockwise)
    ctx3.moveTo(65, 65);
    ctx3.arc(60, 65, 5, 0, Math.PI * 2, true); // Left eye
    ctx3.moveTo(95, 65);
    ctx3.arc(90, 65, 5, 0, Math.PI * 2, true); // Right eye
    ctx3.stroke();
</script>

Draw a rectangle with Canvas and Javascript

Example
Code

<canvas id="canvasRectangle" height="220px" width="auto"></canvas>
<script>
    var canvasRectangle = document.getElementById("canvasRectangle");
    var ctx4 = canvasRectangle.getContext("2d");
    ctx4.beginPath();
    ctx4.rect(25, 25, 250, 150);
    ctx4.stroke();
</script>