Introduction to HTML 5 CANVAS
Have you ever visited a website with a really awesome background animation? Click on the link to see it (you can choose different ones right at the bottom). Have you ever wondered how on earth did they do that? Well, it’s all thanks to a canvas, an HTML5 element.
What exactly is canvas? It’s an HTML element like <div>
or <h1>
but unlike those canvas is used to draw graphics, on the fly, via JavaScript. The <canvas>
element is only a container for graphics. You must use JavaScript to actually draw the graphics and it also has several methods for drawing paths, boxes, circles, text, and adding images.
First things first so let's create a canvas before we go into more details:
<canvas id="c" width="200" height="100"> </canvas>
so this should create a canvas in your HTML file however, you won’t be able to see it so let’s add a border to it as well so we can visually detect it:
<canvas id="c" width="200" height="100" style"border:2px solid black">
</canvas>
So what’s next? How do you start drawing? First, we need to declare in what dimension we want to work (2D or 3D) and create a canvas context variable, which will be using a lot to draw every single element so for that purpose programmers usually make variable for context pretty short, most common are ctx
or c
.
Let's declare our canvas by grabbing it with by id:
const canvas = document.getElementById('c');
and next step is to declare our context:
const ctx = canvas.getContext('2d');
and let’s draw a rectangle:
After writing down everything we’ve talked about before, the next step would be to draw a rectangle by saying ctx.rect() and passing there 4 parameters: the first two would be a position on the canvas in pixels where we would like to place it in x and y dimension, next two is width and height of the rectangle, in our case, it’s a square box that has the same width and length.
Great! Now let’s talk about animation really quickly. How do you make things move on canvas? Since Javascript is a super awesome language and treats our beloved functions as first-class objects, meaning we can do whatever we want with function including calling a function on itself, inside of this function.
I know that would be something that is hard to understand, but here is an amazing blog that my friend wrote about recursive function in Javascript here. So basically you can create a loop that will call a function on itself until certain criteria are met.
And back to animation. Why did I bring up recursive functions? Because what we about to do would be very similar in a way — We’re gonna create an infinite loop by writing a function, let’s call it animate and we’ll write some logic inside, and at the very bottom we’re gonna call a requestAnimationFrame(); function on animate function which will create an infinite loop and whatever we’ll write in the body of our function well be executed over and over and over. This is how animation works, so let’s look at the example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
var cn;
//= document.getElementById('cw');
var c;
var u = 10;
const m = {
x: innerWidth / 2,
y: innerHeight / 2
};
window.onmousemove = function(e) {
m.x = e.clientX;
m.y = e.clientY;
}
function gc() {
var s = "0123456789ABCDEF";
var c = "#";
for (var i = 0; i < 6; i++) {
c += s[Math.ceil(Math.random() * 15)]
}
return c
}
var a = [];
window.onload = function myfunction() {
cn = document.getElementById('cw');
c = cn.getContext('2d');
for (var i = 0; i < 10; i++) {
var r = 30;
var x = Math.random() * (innerWidth - 2 * r) + r;
var y = Math.random() * (innerHeight - 2 * r) + r;
var t = new ob(innerWidth / 2,innerHeight / 2,5,"red",Math.random() * 200 + 20,2);
a.push(t);
}
//cn.style.backgroundColor = "#700bc8";
c.lineWidth = "2";
c.globalAlpha = 0.5;
resize();
anim()
}
window.onresize = function() {
resize();
}
function resize() {
cn.height = innerHeight;
cn.width = innerWidth;
for (var i = 0; i < 101; i++) {
var r = 30;
var x = Math.random() * (innerWidth - 2 * r) + r;
var y = Math.random() * (innerHeight - 2 * r) + r;
a[i] = new ob(innerWidth / 2,innerHeight / 2,4,gc(),Math.random() * 200 + 20,0.02);
}
// a[0] = new ob(innerWidth / 2, innerHeight / 2, 40, "red", 0.05, 0.05);
//a[0].dr();
}
function ob(x, y, r, cc, o, s) {
this.x = x;
this.y = y;
this.r = r;
this.cc = cc;
this.theta = Math.random() * Math.PI * 2;
this.s = s;
this.o = o;
this.t = Math.random() * 150;
this.o = o;
this.dr = function() {
const ls = {
x: this.x,
y: this.y
};
this.theta += this.s;
this.x = m.x + Math.cos(this.theta) * this.t;
this.y = m.y + Math.sin(this.theta) * this.t;
c.beginPath();
c.lineWidth = this.r;
c.strokeStyle = this.cc;
c.moveTo(ls.x, ls.y);
c.lineTo(this.x, this.y);
c.stroke();
c.closePath();
}
}
function anim() {
requestAnimationFrame(anim);
c.fillStyle = "rgba(0,0,0,0.05)";
c.fillRect(0, 0, cn.width, cn.height);
a.forEach(function(e, i) {
e.dr();
});
}
</script>
<style>
#cw {
position: fixed;
z-index: -1;
}
body {
margin: 0;
padding: 0;
background-color: rgba(0,0,0,0.05);
}
</style>
</head>
<body>
<canvas id="cw"></canvas>
</body>
</html>
and the result of that you can see right here:
So this is pretty much it, if you want you can check out my first canvas game I made right here:
Thank you for reading!