Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a circle (not shaded) with Three.js

I am trying to draw a circle very similar to the orbital patterns on this website. I would like to use Three.js instead of pure WebGL.

like image 761
theblang Avatar asked Dec 07 '12 02:12

theblang


People also ask

How do you make a circle in 3 JS?

function createCircle() { let circleGeometry = new THREE. CircleGeometry(1.0, 30.0); circleGeometry. vertices. splice(0, 1); //<= This.

Can three Js do 2D?

JS IS STRUCTURED IN AN ACCESSIBLE WAY. The way that Three. js structures its rendering means that the learning curve won't be too steep. It organizes all of the renders you'll do, whether 3D or 2D, under a “Scene” container.


2 Answers

Three.js r50 added CircleGeometry. It can be seen (albeit with a face) in the WebGL Geometries example.

The first vertex in the geometry is created at the center of the circle (in r84, see CircleGeometry.js line 71, in r65, see CircleGeometry.js line 18), which is nifty if you are going for that "full Pac-Man" or "uninformative pie chart" look. Oh, and it appears to be necessary if you are going to use any material aside from LineBasicMaterial / LineDashedMaterial.

I've verified that the following code works in both r60 & r65:

var radius   = 100,
    segments = 64,
    material = new THREE.LineBasicMaterial( { color: 0x0000ff } ),
    geometry = new THREE.CircleGeometry( radius, segments );

// Remove center vertex
geometry.vertices.shift();

// Non closed circle with one open segment:
scene.add( new THREE.Line( geometry, material ) );

// To get a closed circle use LineLoop instead (see also @jackrugile his comment):
scene.add( new THREE.LineLoop( geometry, material ) );

PS: The "docs" now include a nice CircleGeometry interactive example: https://threejs.org/docs/#api/geometries/CircleGeometry

like image 59
mrienstra Avatar answered Sep 21 '22 05:09

mrienstra


The API changed slightly in newer versions of threejs.

var segmentCount = 32,
    radius = 100,
    geometry = new THREE.Geometry(),
    material = new THREE.LineBasicMaterial({ color: 0xFFFFFF });

for (var i = 0; i <= segmentCount; i++) {
    var theta = (i / segmentCount) * Math.PI * 2;
    geometry.vertices.push(
        new THREE.Vector3(
            Math.cos(theta) * radius,
            Math.sin(theta) * radius,
            0));            
}

scene.add(new THREE.Line(geometry, material));

Modify segmentCount to make the circle smoother or more jagged as needed by your scene. 32 segments will be quite smooth for small circles. For orbits such as those on the site you link you, you may want to have a few hundred.

Modify the order of the three components within the Vector3 constructor to choose the orientation of the circle. As given here, the circle will be aligned to the x/y plane.

like image 42
Drew Noakes Avatar answered Sep 22 '22 05:09

Drew Noakes