-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
66 lines (55 loc) · 1.95 KB
/
script.js
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
const canvas = document.querySelector('canvas')
const generateButton = document.querySelector('.generate-tree-button')
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
let curve = 10;
let curve2 = 0
function drawTree(startX, startY, len, angle, branchWidth, color1, color2){
ctx.beginPath();
ctx.save();
ctx.strokeStyle = color1;
ctx.fillStyle = color2;
ctx.shadowBlur = 5
ctx.shadowColor = 'black'
ctx.lineWidth = branchWidth;
ctx.translate(startX, startY)
ctx.rotate(angle * Math.PI/180);
ctx.moveTo(0,0)
//ctx.lineTo(0, -len)
if(angle > 0){
ctx.bezierCurveTo(curve, -len/2, curve2, -len/2, 0, -len)
}else{
ctx.bezierCurveTo(curve, -len/2, -curve2, -len/2, 0, -len)
}
ctx.stroke();
if(len < 5){
ctx.beginPath();
ctx.arc(0, -len, 10, 0, Math.PI/2)
ctx.fill();
ctx.restore();
return;
}
curve = (Math.random()* 10) + 10
drawTree(0, -len, len * 0.75, angle + curve, branchWidth * 0.6);
drawTree(0, -len, len * 0.75, angle - curve, branchWidth * 0.6);
ctx.restore();
}
drawTree(canvas.width/2, canvas.height - 80, 120, 0, 25, 'brown', 'green')
function generateRandomTree(){
ctx.clearRect(0, 0, canvas.width, canvas.height)
let centerPointX = canvas.width/2
let len = Math.floor((Math.random() * 20) + 100)
let angle = 0
let branchWidth = (Math.random() * 70) + 1
let color1 = 'rgb('+ Math.random() * 255 + ',' + Math.random() * 255 + ','
+ Math.random() * 255 + ')'
let color2 = 'rgb('+ Math.random() * 255 + ',' + Math.random() * 255 + ','
+ Math.random() * 255 + ')'
generateButton.style.background = color1
curve = (Math.random() * 20) + 2
curve2 = Math.random() * 50
drawTree(centerPointX, canvas.height - 80, len, angle, branchWidth, color1,
color2)
}
generateButton.addEventListener('click', generateRandomTree)