<CANVAS>

Tag Description

<canvas> allows us to draw graphics on our page using javascript. New in HTML5.

Code Example

<canvas id="demoCanvas">
canvas element not supported

<script>

// create the canvas variable and set the context
var canvas = document.getElementById("demoCanvas");
var ctx = canvas.getContext("2d");


// create a gradient background
var gradient = ctx.createLinearGradient(0, 0, 0, 200);
gradient.addColorStop(0, "black");
gradient.addColorStop(1, "grey");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 300, 200);

// create a pattern
for (var x = 0.5; x < 300; x += 10) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 200);
}
for (var y = 0.5; y < 200; y += 10) {
ctx.moveTo(0, y);
ctx.lineTo(500, y);
}
ctx.strokeStyle = "#aaa";
ctx.stroke();

// create a filled rectangle
ctx.fillStyle = "red";
ctx.fillRect(15,15, 130,100);

// create a stroke
ctx.strokeStyle = "yellow";
ctx.strokeRect(15,15, 130,100);

// create an empty rectangle
ctx.clearRect(55,25, 20,20);

// create a line
ctx.beginPath();
ctx.moveTo(0, 10);
ctx.lineTo(60, 60);
ctx.lineTo(120, 80);
ctx.lineTo(220, 40);
ctx.lineTo(495, 85);
ctx.strokeStyle = "lime";
ctx.stroke();

// create text
ctx.font = "bold 1.2em sans-serif";
ctx.fillStyle = "pink";
ctx.fillText("canvas example", 150, 25);

// create a circle
ctx.beginPath();
ctx.arc(190, 100, 30, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fillStyle = "violet";
ctx.strokeStyle = "red";
ctx.stroke();
ctx.fill();

</script>

</canvas>

Result

Canvas element not supported

Attributes

Attribute Value Description
width px Default = 300px
height px Default = 150px

Browser Support

Browser Comment
Firefox Yes
Safari Yes
Chrome Yes
Opera Yes
IE 9 Yes
IE <= 8 No (see Notes)

Notes

  • Use Explorercanvas to support CANVAS in IE prior to version 9
Title

details

Thanks for visiting!