-
Notifications
You must be signed in to change notification settings - Fork 1
/
js-ani2.html
62 lines (52 loc) · 2.05 KB
/
js-ani2.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
<?html和css, use requestAnimationFrame method./?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.box{
background-color: lightblue;
height: 20px;
line-height: 20px;
box-sizing: border-box;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
function drawRipple() {
const pixelData = ctx.createImageData(canvas.width, canvas.height);
// Step through the array one pixel at a time
for (let i = 0; i < pixelData.data.length; i += 4) {
// We can find our (x, y) position on the canvas by comparing
// our position in the array with the width of the canvas.
let x = Math.floor(i / 4) % canvas.width;
let y = Math.floor(i / (4 * canvas.width));
// We need our origin to be in the center, so lets convert the (x, y)
// from above (the "canvas coordinates") to their "reindexed" values
// (what they would become if the origin were in the center).
let reIndexedX = -((canvas.width - x) - (canvas.width / 2));
let reIndexedY = (canvas.height - y) - (canvas.height / 2);
// Instead of writing our own code for Pythagorean's theorem, we can
// use JavaScript's built-in method to calculate the hypotenuse.
let distance = Math.hypot(reIndexedX, reIndexedY);
let waveHeight = Math.sin(distance);
// Normally, a sin wave fluctuates between -1 and 1, but we want ours
// to fluctuate between 0 and 255 instead (the range for RGB values).
// Lets adjust the wave height to produce that 0-255 range.
let adjustedHeight = (waveHeight * (255/2)) + (255/2);
// Assign the adjustedHeight to R, G, and B equally, to make gray.
pixelData.data[i] = adjustedHeight; // red
pixelData.data[i + 1] = adjustedHeight; // green
pixelData.data[i + 2] = adjustedHeight; // blue
pixelData.data[i + 3] = 255; // opacity
}
ctx.putImageData(pixelData, 0, 0);
}
drawRipple();
</script>
</body>
</html>