Exercise 16.01
Shapes
var cx = document.querySelector("canvas").getContext("2d");
function parallelogram(x, y) {
cx.beginPath();
cx.moveTo(x, y);
cx.lineTo(x + 50, y);
cx.lineTo(x + 70, y + 50);
cx.lineTo(x - 20, y + 50);
cx.closePath();
cx.stroke();
}
parallelogram(30, 30);
function diamond(x,y){
cx.translate(x +30, y +30);
cx.rotate(Math.PI / 4);
cx.fillStyle = "red";
cx.fillRect(-30, -30, 60, 60);
cx.resetTransform();
}
diamond(140, 30);
function zigzag(x,y){
cx.beginPath();
cx.moveTo(x,y);
for(var i = 0; i < 8; i++){
cx.lineTo(x + 80, y + i * 8 + 4);
cx.lineTo(x,y + i * 8 + 8);
}
cx.stroke();
}
zigzag(240, 20);
function spiral(x,y){
var radius = 50, xCenter = x + radius, yCenter = y + radius;
cx.beginPath();
cx.moveTo(xCenter, yCenter);
for(var i = 0; i < 300; i ++){
var angle = i * Math.PI / 30;
var dist = radius * i / 300;
cx.lineTo(xCenter + Math.cos(angle) * dist, yCenter + Math.sin(angle) * dist);
}
cx.stroke();
}
spiral(340, 20);
function star(x,y){
var radius = 50, xCenter = x + radius, yCenter = y + radius;
cx.beginPath();
cx.moveTo(xCenter + radius, yCenter);
for(var i = 1; i <= 8; i++){
var angle = i * Math.PI / 4;
cx.quadraticCurveTo(xCenter, yCenter, xCenter + Math.cos(angle) * radius, yCenter + Math.sin(angle) * radius);
}
cx.fillStyle = "gold";
cx.fill();
}
star(440, 20);
To open the JavaScript console, press F12 or on MAC press COMMAND-OPTION-I.