canvas
is an HTML element which can be used to draw
graphics. It is an alternative to svg
canvas
element in the html.
Give it an id. It creates a fixed-size drawing surface that
exposes one or more rendering contexts
<!DOCTYPE html>
<meta charset="utf-8">
<!-- Create a div where the graph will take place -->
<canvas id="my_dataviz" width="400" height="400">
</canvas>
<script>
// select the canvas element created in the html
var canvas = document.getElementById('my_dataviz');
// Get the 'context'
var ctx = canvas.getContext('2d');
// Build a rectangle
ctx.fillStyle = '#69b3a2'; // rectangle color
ctx.fillRect(20, 20, 50, 50); // 4 arguments for the rect features: x, y, width and height
</script>
fillRect
: to create a filled rectangle. 4
arguments: x
, y
,
width
and height
.
strokeRect
: to draw just the outlineclearRect
: to clear all the pixel under this
rectangle
<!DOCTYPE html>
<meta charset="utf-8">
<!-- Create a div where the graph will take place -->
<canvas id="my_dataviz2" width="400" height="400">
</canvas>
<script>
// select the canvas element created in the html
var canvas = document.getElementById('my_dataviz2');
// Get the 'context'
var ctx = canvas.getContext('2d');
// Left: filled rectangle
ctx.fillStyle = '#69b3a2'; // rectangle color
ctx.fillRect(10, 10, 50, 50); // 4 arguments for the rect features: x, y, width and height
// Center: rectangle outline
ctx.strokeRect(100, 100, 80, 80);
// Right: rectangle with a cleared area
ctx.fillRect(200, 200, 120, 120);
ctx.clearRect(210, 170, 80, 80);
</script>
beginPath()
.moveTo()
.
lineTo()
to build as many segments as you
need.
fill()
, and/or draw the
stroke with stroke
<!DOCTYPE html>
<meta charset="utf-8">
<!-- Create a div where the graph will take place -->
<canvas id="my_dataviz3" width="400" height="400">
</canvas>
<script>
// select the canvas element created in the html
var canvas = document.getElementById('my_dataviz3');
// Get the 'context'
var ctx = canvas.getContext('2d');
// Set the color:
ctx.fillStyle = '#D8D8D8';
// Initialize path
ctx.beginPath();
// Go to the starting coordinate
ctx.moveTo(100, 50);
// Draw 2 segments
ctx.lineTo(300, 50);
ctx.lineTo(200, 370);
// Fill the shape
ctx.fill();
ctx.stroke();
</script>
arc()
function.
x
, y
,
radius
, startAngle
and
endAngle
.
<!DOCTYPE html>
<meta charset="utf-8">
<!-- Create a div where the graph will take place -->
<canvas id="my_dataviz4" width="400" height="400">
</canvas>
<script>
// select the canvas element created in the html
var canvas = document.getElementById('my_dataviz4');
// Get the 'context'
var ctx = canvas.getContext('2d');
// Set the color:
ctx.fillStyle = '#D8D8D8';
// Initialize path
ctx.beginPath();
// Build a circle
ctx.arc(200, 200, 100, 0, Math.PI * 2)
// Show the stroke
ctx.stroke()
</script>