HTML Canvas
HTML Canvas Graphics
The <canvas> element is used to draw graphics directly on a web page using JavaScript.
What Is HTML Canvas?
The HTML <canvas> element provides a drawable area where graphics are rendered dynamically with JavaScript.
The canvas itself is only a container. All drawing operations are performed through a scripting context.
Canvas supports drawing shapes, paths, text, gradients, and images, and is supported by all modern browsers.
The <canvas> Element
A canvas defines a rectangular drawing area. By default, it has no border and no visible content.
<canvas id="myCanvas" width="200" height="100"></canvas>
Always define an id so the canvas can be accessed via JavaScript, and specify width and height to control its size.
Canvas with Border
A border can be added using CSS.
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
Drawing with JavaScript
To draw on a canvas, JavaScript must first access the canvas element and its 2D rendering context.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
Draw a Line
Lines are created using path methods.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
Draw a Circle
Circles are drawn using the arc() method.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
Draw Text
Canvas can render both filled and outlined text.
Filled Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
Stroked Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World", 10, 50);
Draw Linear Gradient
Linear gradients transition colors along a straight line.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);
Draw Radial Gradient
Radial gradients transition colors outward from a central point.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
ctx.fillStyle = grd;
ctx.fillRect(10, 10, 150, 80);
Draw Image
Images can be drawn onto the canvas using the drawImage() method.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);