Created
April 13, 2017 22:04
-
-
Save animatedlew/929bb3b379f30c6310c74fa9dbb8fd1d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let canvas = document.createElement("canvas"); | |
| canvas.width = 600; | |
| canvas.height = 20; | |
| let ctx = canvas.getContext("2d"); | |
| document.body.appendChild(canvas); | |
| const fps = 60; | |
| const maxlifetime = 1000; | |
| let line = { | |
| x: 20, | |
| y: canvas.height/2, | |
| strength: 40, | |
| lifetime: 0, | |
| vx: 10 | |
| }; | |
| function getLifeFactor() { | |
| return line.lifetime / maxlifetime; | |
| } | |
| function step(time = 0) { | |
| setTimeout(() => { | |
| ctx.fillRect(0, 0, canvas.width, canvas.height); | |
| line.x += line.vx; | |
| if (line.x > canvas.width) line.x = 0; | |
| let f = getLifeFactor(); | |
| let opacity = f > 0.6 ? 1 - f : 1; | |
| let scale = (-Math.cos(f * 2 * Math.PI) + 1) / 2; | |
| ctx.lineWidth = 2 * (1 - f); | |
| ctx.strokeStyle = `rgba(255, 0, 0, ${opacity})`; | |
| ctx.beginPath(); | |
| ctx.moveTo(line.x - scale * line.strength, line.y); | |
| ctx.lineTo(line.x + line.vx, canvas.height/2); | |
| ctx.stroke(); | |
| line.lifetime += 1000/fps; | |
| if (line.lifetime > maxlifetime) { | |
| line.x = 0; | |
| line.lifetime = 0; | |
| } | |
| requestAnimationFrame(step); | |
| }, 1000/fps); | |
| } | |
| requestAnimationFrame(step); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment