会想写这篇文章主要是想找个地方记一记用js如何随机变换颜色

下面是代码

html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random canvas circles</title>
</head>
<body>

<button>Update</button>

<canvas></canvas>

</body>
</html>

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
html {
width: 100%;
height: inherit;
}
canvas {
display: block;
}
body {
margin: 0;
}
button {
position: absolute;
top: 5px;
left: 5px;
}

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
var btn = document.querySelector('button');
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var WIDTH = document.documentElement.clientWidth;
var HEIGHT = document.documentElement.clientHeight;
canvas.width = WIDTH;
canvas.height = HEIGHT;
function random(number) {
return Math.floor(Math.random()*number);
}
// 颜色的随机变化
function bg() {
var r = random(256);
var g = random(256);
var b = random(256);
// return "rgb("+r+','+g+','+b+")";
return `rgba(${r},${g},${b},0.7)`;
}
function draw() {
ctx.clearRect(0,0,WIDTH,HEIGHT);
for(var i = 0; i < 100; i++) {
ctx.beginPath();
ctx.fillStyle = bg();
// ctx.fillStyle = 'rgba(255,0,0,0.6)';
// 大小的随机变化
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
ctx.fill();
}
}
btn.addEventListener('click',draw);

黑暗的日子都是我带来的

都是因为我才会一直吵架

都是因为我才会如此疲倦