Last active
August 29, 2015 14:15
-
-
Save asauber/3d266a42c442dfeab94a to your computer and use it in GitHub Desktop.
demonstration of numeric integration with animation
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
function simulate() { | |
var theCanvas = document.getElementById("the-canvas"); | |
var theContext = theCanvas.getContext('2d'); | |
theContext.translate(theCanvas.width / 2, theCanvas.height / 2); | |
var radius = 60; | |
var amplitude = theCanvas.height / 2 - radius - 10; | |
var sinBall = { | |
x: 0, | |
y: 0, | |
initialY: 0 | |
}; | |
var integratedSinBall = { | |
x: 0, | |
y: 0 + amplitude, | |
initialY: 0 + amplitude | |
}; | |
var currentTime = 0; | |
var timeDelta = 0.015; | |
var currentSinValue = 0; | |
var chunkSinValue = 0; | |
function drawAxes() { | |
theContext.beginPath(); | |
theContext.strokeStyle = "black"; | |
theContext.moveTo(-theCanvas.width / 2, 0); | |
theContext.lineTo(theCanvas.width / 2, 0); | |
theContext.stroke(); | |
} | |
function drawBall(theBall, theColor) { | |
theContext.beginPath(); | |
theContext.arc(theBall.x, theBall.y, radius, 0, 2 * Math.PI, false); | |
theContext.fillStyle = theColor; | |
theContext.fill(); | |
}; | |
function drawScreen() { | |
// clear the canvas | |
theContext.fillStyle = '#ffe6dc'; | |
theContext.fillRect(-theCanvas.width / 2, -theCanvas.height / 2, theCanvas.width, theCanvas.height); | |
drawAxes(); | |
drawBall(sinBall, '#1d80d2'); | |
drawBall(integratedSinBall, '#65ace6'); | |
currentSinValue = Math.sin(currentTime); | |
currentTime += timeDelta; | |
chunkSinValue = timeDelta * currentSinValue; | |
sinBall.y = sinBall.initialY - currentSinValue * amplitude; | |
integratedSinBall.y -= chunkSinValue * amplitude; | |
}; | |
function animationLoop() { | |
window.setTimeout(animationLoop, 20); | |
drawScreen(); | |
} | |
animationLoop(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment