#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# Converting webgl 3d coordinates to 2d screen coordinates (p5.js)

I'm trying to map html text on top of a webgl p5.js sphere of nodes that is rotating. I know I have to do something with a projection matrix and a view matrix in order to convert from 3d space to 2d but not sure how to get the matrix of the camera, if that's what I'm supposed to do? I found this which looked promising http://webglfactory.blogspot.co.uk/2011/05/how-to-convert-world-to-screen.html

You can see an Instagram vid example here: http://brendandawes.com/blog/07-31-471

Any help would be great. Incidentally I did something similar when using Three.js but I could get the projection matrix, with he p5.js one I'm not sure how I get that.

Tagged:

• So I've got a bit further. I realised that I needed to 3D rotate the vectors but p5.js doesn't support 3d rotation of vectors. So I found this function online which seemed to do the job.

``````this.rotateAround = function(vector,axis, theta) {

// en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
// en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix
var p1 = vector;
var p = [ p1.x, p1.y, p1.z ]; // the point being rotated
var a = axis;          // the axis being rotated around
var s = Math.sin(theta);
var c = Math.cos(theta);
// quaternion-derived rotation matrix
var q = [
[ a.x*a.x*(1-c) + c,     a.x*a.y*(1-c) - a.z*s, a.x*a.z*(1-c) + a.y*s],
[ a.y*a.x*(1-c) + a.z*s, a.y*a.y*(1-c) + c,     a.y*a.z*(1-c) - a.x*s],
[ a.z*a.x*(1-c) - a.y*s, a.z*a.y*(1-c) + a.x*s, a.z*a.z*(1-c) + c    ],
];
// multiply q × p
var qp = [0, 0, 0];
for (var i=0; i<3; i++) {
for (var j=0; j<3; j++) {
qp[i] += q[i][j] * p[j];
}
}
var p2 = createVector(qp, qp, qp);
return p2;
// qv en.wikipedia.org/wiki/Rodrigues'_rotation_formula...
};
``````

Then I found this online too which goes some way too mapping the 3d coords to the screen

``````var xp = rot.x * scale / (rot.z + scale);
var yp = rot.y * scale / (rot.z + scale);
``````

Certainly getting there if you have a look at this http://www.brendandawes.com/blog/08-01-473 but still not right.

• screenX, screenY?

• P5.js doesn't have screenX or screenY unfortunately.