|
Voici un exemple écrit en Canvas-HTML5 qui modélise le mouvement d'un pendule simple. La méthode numérique
utilisée est rk4 (runge kutta ordre 4).
Le source est visible ci-dessous. On commence par initialiser l'interface
graphique , mettre la fonction utilisée dans la méthode de runge kutta
et traduisant l'équation différentielle du mouvement. Ensuite, nous calculons les
coefficients pour avoir la prochaine valeur de l'angle theta, puis mettons à jour l'affichage de la nouvelle
valeur.
/*** Pendulum rk4 ***/
var canvas;
var g = 9.81;
var h = 0.01;
var step = 15;
var l = 1;
var le = 190;
var radius = 5;
var x0 = 200;
var y0 = 50;
var x1 = 0;
var y1 = 0;
var old_x1 = 0;
var old_y1 = 0;
var theta = 0;
var dtheta_dt = 0;
var old_theta = 0;
var k = new Array(2);
for (var i = 0; i < 2; i++)
k[i] = new Array(4);
function F(theta, g, l) {
var result;
result = (g/l)* Math.cos(theta);
return result;
}
function ProcessNext() {
k[0][0]=h*F(theta,g,l);
k[0][1]=h*(dtheta_dt);
k[0][2]=h*F((theta+(k[0][1]/2)),g,l);
k[0][3]=h*(dtheta_dt+k[0][0]/2);
k[1][0]=h*F((theta+(k[0][3]/2)),g,l);
k[1][1]=h*(dtheta_dt+k[0][2]/2);
k[1][2]=h*F((theta+k[1][1]),g,l);
k[1][3]=h*(dtheta_dt+k[1][0]);
/** Save old **/
old_theta = theta;
/** Process next **/
theta=theta+((k[0][1]+2*(k[0][3]+k[1][1])+k[1][3])/6);
dtheta_dt=dtheta_dt+((k[0][0]+2*(k[0][2]+k[1][0])+k[1][2])/6);
setTimeout(function() {DrawPend(canvas);},step);
}
function DrawPend(canvas) {
var context = canvas.getContext('2d');
x1 = x0+le*Math.cos(theta);
y1 = y0+le*Math.sin(theta);
old_x1 = x0 + le*Math.cos(old_theta);
old_y1 = y0 + le*Math.sin(old_theta);
context.fillStyle = 'white';
context.fillRect(0, 0, 400, 320);
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.closePath();
context.strokeStyle = 'black';
context.stroke();
context.beginPath();
context.arc(x1, y1, radius, 0, 2*Math.PI, true);
context.closePath();
context.fillStyle = 'blue';
context.fill();
ProcessNext();
}
function main() {
canvas = document.getElementById('penduleCanvas');
DrawPend(canvas);
}
window.onload = function() {
main();
}
|
|