HTML Canvas Graphics

HTML Tutorial

HTML Forms

HTML Graphics

HTML Media

HTML API

HTML Canvas Graphics

The HTML <canvas> element helps to draw graphics on a web page.

What is HTML Canvas?

  • The HTML <canvas> element draws graphics, on the fly, through JavaScript.
  • The <canvas> element acts as a container only for graphics. JavaScript must be used to actually draw the graphics.
  • Canvas provides several methods for drawing paths, boxes, circles, text, and adding images.

Canvas Examples

				
					<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
				
			

Add a JavaScript.

After the rectangular canvas area is created, JavaScript should be added to do the drawing.

Here are some examples:

Draw a Line

				
					<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>

				
			

Output:

canvas line

Draw A Circle

				
					<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>

				
			

Output:

Draw A Text

				
					<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
</script>

				
			

Output:

Hello World

Draw a linear Gradient

				
					<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>
<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>

				
			

Output:

linear gradient

Draw Circular Gradient

				
					<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML canvas tag.</canvas>
<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>

				
			

Output:

circular gradient