Last active
March 24, 2018 22:17
-
-
Save chabb/bdeb063e24b66d6a12a2d3c57e91bdb1 to your computer and use it in GitHub Desktop.
Spring based on sin
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
| <canvas id="canvas" width="600px" height="400px"></canvas> | |
| <script src="./index.js"></script> |
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 x = 50 , y = 0, w = 150, h = 100; | |
| let angle = 0, frequency = 5.0; | |
| let amplitude = 30, damping = .98; | |
| let springSegments = 32, springWidth = 15; | |
| let width = 600, height = 400; | |
| let canvas = document.getElementById('canvas'); | |
| let ctx = canvas.getContext('2d'); | |
| canvas.width = width; | |
| canvas.height = height; | |
| function setup() { | |
| x = width / 2.0 - w / 2.0; | |
| ctx.lineWidth = 1; | |
| ctx.strokeStyle = '#000000'; | |
| ctx.fillStyle = '#000000'; | |
| ctx.translate(0.5, 0.5); | |
| } | |
| function draw() { | |
| ctx.clearRect(0, 0, width, height); | |
| createSpring(); | |
| startSpring(); | |
| window.requestAnimationFrame(draw); | |
| } | |
| function createSpring() { | |
| ctx.beginPath(); | |
| ctx.moveTo(x + 20, y); | |
| ctx.lineTo(x + w - 20, y); | |
| ctx.lineTo(x + w, y + h); | |
| ctx.lineTo(x, y + h); | |
| ctx.closePath(); | |
| ctx.stroke(); | |
| ctx.fill(); | |
| ctx.beginPath(); | |
| for (let i = 0; i < springSegments; i++) { | |
| if (i === springSegments - 1) { | |
| ctx.lineTo(x + w / 2 + springWidth, | |
| (y / springSegments) * i); | |
| ctx.lineTo( | |
| x + w / 2, | |
| ( y / springSegments) * (i + 1)); | |
| } else { | |
| if (i % 2 === 0) { | |
| ctx.lineTo(x + w / 2 - springWidth, | |
| (y / springSegments) * i); | |
| ctx.lineTo( | |
| x + w / 2 + springWidth, | |
| ( y / springSegments) * (i + 1)); | |
| } else { | |
| ctx.lineTo(x + w / 2 - springWidth, | |
| (y / springSegments) * i); | |
| ctx.lineTo( | |
| x + w / 2 - springWidth, | |
| ( y / springSegments) * (i + 1)); | |
| } | |
| } | |
| } | |
| ctx.stroke(); | |
| } | |
| setup(); | |
| draw(); | |
| function startSpring(){ | |
| // en gros, plus la frequence est elevee plus vite on va decelerer et re-accelere | |
| // MAIS le damping va faire que peu a peu, on 'perd' de l'energie, jusqu'a ce qu'on s'arrete | |
| y += Math.cos(Math.PI/180 * angle) * amplitude; | |
| amplitude *= damping; | |
| angle+= frequency; | |
| } | |
| function setSpring() { | |
| y = 100; | |
| angle = 0; | |
| amplitude = 26.0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment