Tired of text? We can actually draw with JavaScript using a canvas.
again, a canvas is an html element - it’s a tag. You can draw on it by using JavaScript. Here’s how you set it up:
Let’s start with our usual template….
<html>
<head>
<title></title>
</head>
<body>
<script>
</script>
</body>
</html>
We’ll have to let the page know that it should start drawing once the entire page is loaded.
<body onload="draw()">
Let’s add a place to draw!. Use a pair of opening and closing tags called canvas… with attributes, id, width, and height.
<canvas id="sketch" width="300" height="300">
</canvas>
As usual, add your script tags:
<script>
</script>
Within your script tags, define the function that you specified in your body tag.
<script>
function draw() {
// your drawing goes here
}
</script>
In order to draw on your canvas, you have to:
<script>
var sketch = document.getElementById('sketch');
var context = sketch.getContext("2d");
</script>
Here’s everything put together.
<html>
<head>
<title></title>
</head>
<body onload="draw()">
<canvas id="sketch" width="300" height="300">
</canvas>
<script>
function draw() {
var sketch = document.getElementById('sketch');
var context = sketch.getContext("2d");
// draw stuff here!
}
</script>
</body>
</html>
About the canvas…
Once you have your context, you can call methods (or functions) from the context by using the dot and the function name:
context.fillRect(30, 30, 50, 50);
fillRect creates a rectangle. It takes 4 arguments:
context.fillRect(x, y, width, height);
A circle is a bit more complicated:
context.beginPath();
context.arc(x, y, radius, start angle, end angle, clockwise);
context.closePath();
context.fill();
context.beginPath();
context.arc(30, 10, 10, 0, 2 * Math.PI, true);
context.closePath();
context.fill();
You can color your shapes by setting fillStyle:
context.fillStyle = "#00ff00"
Each shape you create draws on top of all of your previous drawwings. In this case, the green circle is drawn over the black square:
context.fillRect(40, 30, 100, 100);
context.fillStyle = "#00ff00"
context.beginPath();
context.arc(50, 40, 40, 0, 2 * Math.PI, true);
context.closePath();
context.fill();
<body onload="draw()">
<canvas id="sketch" width="300" height="300">
</canvas>
<script>
function draw() {
var sketch = document.getElementById('sketch');
var context = sketch.getContext("2d");
context.fillRect(40, 30, 100, 100);
context.fillStyle = "#00ff00"
context.beginPath();
context.arc(50, 40, 40, 0, 2 * Math.PI, true);
context.closePath();
context.fill();
}
</script>
</body>