This repository has been archived by the owner on Mar 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
shapes.html
85 lines (75 loc) · 2.63 KB
/
shapes.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<!--
1 - Shapes (19/3/2020)
Write a program that draws the following shapes on a canvas:
1. A trapezoid (a rectangle that is wider on one side)
2. A red diamond (a rectangle rotated 45 degrees or ¼π radians)
3. A zigzagging line
4. A spiral made up of 100 straight line segments
5. A yellow star
When drawing the last two, you may want to refer to the explanation of `Math.cos` and `Math.sin` in Chapter 14, which describes how to get coordinates on a circle using these functions.
I recommend creating a function for each shape. Pass the position, and optionally other properties such as the size or the number of points, as parameters. The alternative, which is to hard-code numbers all over your code, tends to make the code needlessly hard to read and modify.
-->
<!DOCTYPE html>
<canvas width="600" height="200"></canvas>
<script>
let cx = document.querySelector("canvas").getContext("2d");
function trapezoid(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();
}
trapezoid(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 (let 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) {
let radius = 50;
let xCenter = x + radius;
let yCenter = y + radius;
cx.beginPath();
cx.moveTo(xCenter, yCenter);
for (let i = 0; i < 300; i++) {
let angle = i * Math.PI / 30;
let 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) {
let radius = 50;
let xCenter = x + radius;
let yCenter = y + radius;
cx.beginPath();
cx.moveTo(xCenter + radius, yCenter);
for (let i = 1; i <= 8; i++) {
let 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);
</script>