The Canvas API provides a means for drawing graphics via JavaScript and the HTML element:
Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.
The canvas is initially blank. To display something, a script first needs to access the rendering context and draw on it.
function draw() {
const canvas = document.getElementById('tutorial');
const ctx = canvas.getContext('2d');
}
fillRect(x, y, width, height) // Draws a filled rectangle
strokeRect(x, y, width, height) // Draws a rectangular outline
clearRect(x, y, width, height) // Clears rectangular area
function draw() {
const canvas = document.getElementById('canvas');
if (canvas.getContext){
const ctx = canvas.getContext('2d');
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
}
}
beginPath()
Path methods; closePath()
stroke(); fill()
function draw() {
const canvas = document.getElementById('canvas');
if (canvas.getContext){
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75,50);
ctx.lineTo(100,75);
ctx.lineTo(100,25);
ctx.fill();
}
}
If we want to apply colors to a shape, there are two important properties we can use: fillStyle and strokeStyle.
// these all set the fillStyle to 'orange'
ctx.fillStyle = "orange";
ctx.fillStyle = "#FFA500";
ctx.fillStyle = "rgb(255,165,0)";
ctx.fillStyle = "rgba(255,165,0,1)";
Two methods which are indispensable once you start generating ever more complex drawings.
save(); restore();
setInterval(function, delay) // no user interaction
setTimeout(function, delay) // use keyboard or mouse events
requestAnimationFrame(callback) // user interaction
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.globalCompositeOperation = 'destination-over';
ctx.clearRect(0,0,300,300); // clear canvas
ctx.fillStyle = 'rgba(0,0,0,0.4)';
ctx.strokeStyle = 'rgba(0,153,255,0.4)';
ctx.save(); // save state
// Draw smth
ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );
ctx.translate(105,0);
ctx.fillRect(0,-12,50,24);
ctx.drawImage(earth,-12,-12);
......
ctx.restore(); // restore state
window.requestAnimationFrame(draw);
}
The Canvas API is extremely powerful, but not always simple to use. The libraries listed below can make the creation of canvas-based projects faster and easier.