我正在用Javascript创建一个交互式太阳能系统画布。
行星用三角函数围绕太阳旋转。这个特殊的代码是为我编写的,所以我不知道它是如何工作的。
为了使行星正确定位,使它们围绕太阳完全旋转,我只能定位它们的x轴而不接触它们的y轴。但每当我刷新页面时,他们都会从非常不切实际的位置开始。这可以通过知道如何正确定位它们或改变行星的速度来解决。
以下是大部分相关代码:
function initCanvas(){
var ctx = document.getElementById('my_canvas').getContext('2d');
var dynamicSunW = 25;
var dynamicSunH = 0;
var dynamicSunX = (ctx.canvas.width * .5) - (Math.PI* 1 * .5);
//dynamicSun is always at dead center of canvas
var dynamicSunY = (ctx.canvas.height * .5) - (dynamicSunH * .5);
var angleOfSun = 0;
var posMercuryX = (ctx.canvas.width * .5) - (Math.PI* 1 * .5) - 50;
var posMercuryY = (ctx.canvas.height * .5) - (dynamicSunH * .5) + 20;
var gravityMercury = {x: posMercuryX, y: posMercuryY };
var posVenusX = (ctx.canvas.width * .5) - (Math.PI* 1 * .5) - 50;
var posVenusY = (ctx.canvas.height * .5) - (dynamicSunH * .5) + 46;
var gravityVenus = {x: posVenusX, y: posVenusY };
/*these variables with lots of calculations behind them simply represent
dynamic positions based on canvas width and height so that whenever i change
the canvas size, the positions will still be the same in relation to the size
*/
//this code was not written by, the trigonometric function
function rotate_point(pointX, pointY, originX, originY, ang) {
ang = Math.PI / 180.0;
return {
x: Math.cos(ang) * (pointX-originX) -
Math.sin(ang) * (pointY-originY) + originX ,
y: Math.sin(ang) * (pointX-originX) +
Math.cos(ang) * (pointY-originY) + originY
};
}
//an array of each planet with their own position, size and style
var Solarsystem = {
Venus: {
render: function(){
ctx.beginPath();
gravityVenus = rotate_point(gravityVenus.x, gravityVenus.y,
dynamicSunX, dynamicSunY, angleOfSun);
ctx.arc(gravityVenus.x,gravityVenus.y ,7, 0, 2*Math.PI);
ctx.fillStyle = "rgba(255,165,0,1)";
ctx.closePath();
ctx.fill();
}
}
, Mercury: {
render: function(){
ctx.beginPath();
gravityMercury = rotate_point(gravityMercury.x,
gravityMercury.y,
dynamicSunX, dynamicSunY - 2, angleOfSun);
ctx.arc(gravityMercury.x,gravityMercury.y ,5, 0, 2*Math.PI);
ctx.fillStyle = "rgba(119,136,153,1)";
ctx.closePath();
ctx.fill();
ctx.stroke();
}
}
, Sun: {
render: function(){
ctx.fillStyle = "rgba(255,255,51,1)";
ctx.save(); //store ctx so it can be later reused
ctx.shadowColor = 'yellow';
ctx.shadowBlur = 70;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.beginPath();
ctx.arc(dynamicSunX, dynamicSunY, dynamicSunW,
dynamicSunH, Math.PI*2, true);
ctx.closePath();
ctx.fill();
ctx.restore(); //ctx at time of save
以下是我设置动画间隔的方法
function animate(){
background.render();
Solarsystem.Neptune.render();
Solarsystem.Uranus.render();
Solarsystem.Saturn.render();
Solarsystem.Jupiter.render();
Solarsystem.Mars.render();
Solarsystem.Earth.render();
Solarsystem.Venus.render();
Solarsystem.Mercury.render();
Solarsystem.Sun.render();
}
var animateInterval = setInterval(animate, 1000/60);
PS:我问过一个关于如何加速每个星球的不同问题。我还在等待答案。如果你知道怎么做,请给我一个答案!
Redis