The graphic on the left is generated using the <canvas> element. It features four components: a red rectangle, a gradient rectangle, a multicolor rectangle, and multicolor text.
The HTML <canvas> element is employed to dynamically draw graphics using JavaScript.
While the <canvas> element itself is merely a container for graphics, you need JavaScript to render the graphics.
The canvas provides numerous methods for drawing paths, rectangles, circles, text, and incorporating images.
All major browsers support the canvas element.
A canvas is a rectangular region on an HTML page. By default, it has no border and contains no content.
The HTML code appears as follows:
<canvas id=”myCanvas” width=”200″ height=”100″></canvas> |
Note: Always include an |
Here is an example of a simple, empty canvas:
Example
<canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid #000000;”> </canvas> |
After creating the rectangular canvas area, you need to add JavaScript to perform the drawing.
Here are some examples:
Example
<script> var c = document.getElementById(“myCanvas”); var ctx = c.getContext(“2d”); ctx.moveTo(0, 0); ctx.lineTo(200, 100); ctx.stroke(); </script> |
Example
<script> var c = document.getElementById(“myCanvas”); var ctx = c.getContext(“2d”); ctx.beginPath(); ctx.arc(95, 50, 40, 0, 2 * Math.PI); ctx.stroke(); </script> |
Example
<script> var c = document.getElementById(“myCanvas”); var ctx = c.getContext(“2d”); ctx.font = “30px Arial”; ctx.fillText(“Hello World”, 10, 50); </script> |
Example
<script> var c = document.getElementById(“myCanvas”); var ctx = c.getContext(“2d”); ctx.font = “30px Arial”; ctx.strokeText(“Hello World”, 10, 50); </script> |
Example
<script> var c = document.getElementById(“myCanvas”); var ctx = c.getContext(“2d”); // Create gradient var grd = ctx.createLinearGradient(0, 0, 200, 0); grd.addColorStop(0, “red”); grd.addColorStop(1, “white”); // Fill with gradient ctx.fillStyle = grd; ctx.fillRect(10, 10, 150, 80); </script> |
Example
<script> var c = document.getElementById(“myCanvas”); var ctx = c.getContext(“2d”); // Create gradient var grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100); grd.addColorStop(0, “red”); grd.addColorStop(1, “white”); // Fill with gradient ctx.fillStyle = grd; ctx.fillRect(10, 10, 150, 80); </script> |
<script> var c = document.getElementById(“myCanvas”); var ctx = c.getContext(“2d”); var img = document.getElementById(“scream”); ctx.drawImage(img, 10, 10); </script> |