Skip to content

Instantly share code, notes, and snippets.

@yuanliwei
Created November 8, 2018 18:09
Show Gist options
  • Save yuanliwei/4941eea368d55295086f29d8fc959d1b to your computer and use it in GitHub Desktop.
Save yuanliwei/4941eea368d55295086f29d8fc959d1b to your computer and use it in GitHub Desktop.
canvas wave
<div class="">
<canvas id="canvas" width="400" height="150"></canvas>
</div>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ratio = window.devicePixelRatio;
canvas.width = canvas.clientWidth * ratio;
canvas.height = canvas.clientHeight * ratio;
var width = canvas.width;
var height = canvas.height;
var time = 0;
ctx.fillStyle = "rgba(255, 255, 255, 0.3)";
var offsets = [
Math.PI / 6 * 1,
Math.PI / 6 * 2,
Math.PI / 6 * 3,
Math.PI / 6 * 4,
Math.PI / 6 * 5,
Math.PI / 6 * 6
];
var maxs = [
height / 3,
height / 3.3,
height / 2.2,
height / 3.2,
height / 2.5,
height / 3.6
];
var steps = [150, 330, 210, 280, 240, 160];
var colors = ["red", "pink", "blue", "green", "red", "black"];
function loop() {
time += 0.05;
requestAnimationFrame(loop);
ctx.fillRect(0, 0, width, height);
for (var i = 0; i < offsets.length; i++) {
drawLine(
ctx,
time,
offsets[i],
maxs[i],
steps[i],
width,
height,
colors[i]
);
}
}
function drawLine(ctx, time, offset, max, step, width, height, color) {
max *= 1.5;
var left = -((width / 2 + time * 10) % (2 * step));
var x1,
y1,
x2,
y2,
xo,
yo,
revert = 1;
ctx.strokeStyle = color;
y1 = y2 = height / 2;
do {
x1 = left;
x2 = x1 + step;
xo = x1 + step / 2;
yo = revert * max * Math.sin(time + offset) / 2 + height / 2;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.quadraticCurveTo(xo, yo, x2, y2);
ctx.stroke();
ctx.closePath();
left += step;
revert *= -1;
} while (left < width);
}
loop();
html,
body {
width: 100%;
height: 100%;
background: #ccc;
padding: 0px;
margin: 0px;
overflow: hidden;
}
canvas {
width: 400px;
height: 150px;
background: #fff;
margin: 100px auto;
}
div {
text-align: center;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment