2016-01-24 38 views
0

我正在尝试创建一个黑洞模拟,该模拟将显示一个黑洞和100个远离它的圈子,速度会因重力而下降。这里是我的代码:如何使用canvas和javascript动画100个圈子?

<!DOCTYPE html> 
    <html lang="en"> 
<head> 
<meta charset="utf-8" /> 
<title>test trou noir</title> 
<script> 
var canvas = document.getElementById ("space"); 
var ctx = canvas.getContext ('2d'); 
var blackhole; 
var circle = new Array(); 

window.onload = init; 

function init(){ 
var G = 6.67e-11, //gravitational constant 
c = 3e8, //speed of light (m/s) 
M = 12e31, // masseof the blackhole in kg (60 solar masses) 
Rs = (2 * G * M)/9e16, //Schwarzchild radius 
    pixel_Rs = Rs/1e3;// scaled radius 

    blackhole = new Ball (pixel_Rs, 700, 400, "black"); 
    blackhole.draw(); 
}; 

function Ball (radius, posX, posY, color){ 
this.radius = radius; 
    this.posX = posX; 
    this.posY = posY; 
    this.color = color; 
} 
Ball.prototype.draw = function (ctx){ 
    var ctx = canvas.getContext ('2d'); 
    ctx.fillStyle = this.color; 
    ctx.beginPath(); 
    ctx.arc (this.posX, this.posY, this.radius, 0, 2*Math.PI); 
    ctx.closePath(); 
    ctx.fill(); 
}; 

    </script> 
    <style> 
    body { 
    background-color:#021c36 ; 
margin: 0px;} 
</style> 
</head> 
<body> 
    <canvas id ="space", width = "1400", height = "800"> 
</canvas> 
</body> 
    </html> 

谁能告诉我为什么我不能让画布绘制黑洞,以及如何创建这100圆和它们的动画,我从字面上尝试了一切,我不能使其工作 非常感谢

+3

我认为你只是看不到黑洞,因为它不发光:)而且可能你需要为你的画布添加到HTML主体 – Gavriel

+0

上,以显示你画的黑色圆弧,你需要在你的文档中画一个画布,把你的脚本包装在一个'onload '事件,要移除'blackhole.draw(ctx)'中的'ctx'或实际将调用传递给context2d,并且还必须确保画布的宽度和高度属性设置为> 1000。你的移动圈子,这是一个SO格式太广泛的问题。 – Kaiido

+0

但我确实把画布标签(我可能复制/粘贴错误),我不明白为什么它不画黑圈 –

回答

0

你错过了从HTML画布:

<canvas id="space"/> 

你需要传递CTX您绘制函数:

blackhole.draw(ctx); 

虽然它仍然没有画,但那可能是因为尺寸/颜色。

更新:

这里有一个版本,你可以看到:https://jsfiddle.net/gjwh33mq/2/从这里你可以逐步改变数字。 (有一些奇怪的bug,window.onload没有被调用,所以我在js的末尾添加了一个调用)

+0

你是什么意思,它可能是因为颜色 –

+0

https://jsfiddle.net/gjwh33mq/我的意思是你可能画到一个点的画布大小以外。所有这些巨大的数字....试着画一个小圆圈到画布上的已知位置,然后开始将数字改变为真实的物理值。你可能需要在这里缩放一些东西,因为你没有足够的画布大小恕我直言 – Gavriel

+0

看到我最近的更新,你甚至可以看到你的黑洞:) – Gavriel