gpt4 book ai didi

javascript - HTML5 Javascript 轮换

转载 作者:行者123 更新时间:2023-12-02 19:12:07 27 4
gpt4 key购买 nike

我是 JavaScript(和编程)新手,正在努力解决如何在 HTML5 Canvas 中添加旋转的问题。我基本上是试图让一个 JavaScript 对象围绕另一个对象旋转。就我而言,我需要让一颗行星绕太阳运行。

我目前在绘图函数中声明了行星,它们显示得很好。我只需要有关如何添加旋转的帮助。

感谢您的宝贵时间。

最佳答案

这是一个简单的示例:http://jsfiddle.net/FTMCv/1/

我创建的 CelestialBody 类仅考虑圆形轨道,因此它不是完美的模拟,但在大多数情况下可能就足够了。

(function(){

var can = document.getElementById('planetarium'),
ctx = can.getContext('2d'),
bodies = [];


(function init(){
var orbCenter = {x:can.width/2, y:can.height/2};

bodies.push(new CelestialBody(
50, orbCenter , 0, 0));

bodies.push(new CelestialBody(
15, orbCenter , 250, -.2));
bodies.push(new CelestialBody(
6, orbCenter , 200, .3));
bodies.push(new CelestialBody(
7, orbCenter , 150, .5));
bodies.push(new CelestialBody(
5, orbCenter , 100, 1));
bodies.push(new CelestialBody(
4, orbCenter , 75, 3));
})();

function CelestialBody(radius, orbitalCenter, orbitalDistance, orbitalVelocity){
var pos = {x:0, y:0},
rad = radius,
orb = {x: orbitalCenter.x, y:orbitalCenter.y},
ove = orbitalVelocity,
odi = orbitalDistance;

var update = function(){
var cAng = Math.atan2(pos.y - orb.y, pos.x - orb.x);
var rAng = cAng + ove * Math.PI/180;

pos.x = orb.x + Math.cos(rAng) * odi;
pos.y = orb.y + Math.sin(rAng) * odi;
};

this.draw = function(ctx){
update();

ctx.beginPath();
ctx.fillStyle = "#fff";
ctx.arc(pos.x,pos.y, rad, 0, 2*Math.PI);
ctx.fill();
};

(function init(){
pos.y = orb.y;
pos.x = orb.x + odi;
})();
}

(function draw(){
ctx.clearRect(0,0,can.width,can.height);

for(var i = 0; i < bodies.length; i++)
bodies[i].draw(ctx);

webkitRequestAnimationFrame(draw);
})();

})();​

关于javascript - HTML5 Javascript 轮换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590592/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com