-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path30_canva_绘制星空_背景渐变.html
71 lines (56 loc) · 1.67 KB
/
30_canva_绘制星空_背景渐变.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<canvas id="myCanvas" style="border:1px solid red;">
当前浏览器不支持canvas,请更换浏览器后再试
</canvas>
<script>
window.onload = function () {
var canvas = document.getElementById('myCanvas')
canvas.width = 1200
canvas.height = 800
var ctx = canvas.getContext('2d')
// 绘制背景
var grd = ctx.createLinearGradient(0, 0, 0, 800)
grd.addColorStop(0.0, '#000')
grd.addColorStop(1.0, '#035')
ctx.fillStyle = grd
ctx.fillRect(0, 0, canvas.width, canvas.height)
// 绘制星星
for (var i = 0; i < 200; i++) {
var r = Math.random() * 10 + 10
var x = Math.random() * canvas.width
var y = Math.random() * canvas.height * 0.55
var rot = Math.random() * 360
drawStar(ctx, x, y, r, r / 2, rot)
}
}
function drawStar(ctx, x, y, R, r, rot) {
ctx.save()
ctx.translate(x, y)
ctx.rotate(rot / 180 * Math.PI)
ctx.scale(R, R)
starPath(ctx)
ctx.fillStyle = '#fb3'
ctx.fill()
ctx.restore()
}
function starPath(ctx) {
ctx.beginPath()
for (var i = 0; i < 5; i++) {
ctx.lineTo(Math.cos((18 + i * 72) / 180 * Math.PI),
-Math.sin((18 + i * 72) / 180 * Math.PI))
ctx.lineTo(Math.cos((54 + i * 72) / 180 * Math.PI) * 0.5,
-Math.sin((54 + i * 72) / 180 * Math.PI) * 0.5)
}
ctx.closePath()
}
</script>
</body>
</html>