SmartCodingTips

Canvas in HTML5

The <canvas> element in HTML5 is used to draw graphics on a web page via JavaScript. It can be used for rendering graphs, game visuals, art, image manipulation, and more.

Canvas Syntax

The <canvas> element creates a drawable region in your HTML, which is accessed and manipulated using JavaScript.


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

Basic Drawing with JavaScript

To draw on the canvas, you need to access its context in JavaScript:


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

Common Canvas Methods

  • fillRect(x, y, width, height) – Draws a filled rectangle
  • strokeRect(x, y, width, height) – Draws a rectangular outline
  • clearRect(x, y, width, height) – Clears the specified area
  • beginPath(), moveTo(), lineTo(), stroke() – For drawing paths
  • arc() – For drawing circles and arcs
  • fillText(), strokeText() – To draw text