I am new to Three.js and I'm trying to implement the technique used in Microsoft Paint for drawing a line segment. I'm trying to get coordinates of a point onMouseDown then extend a line with onMouseMove until onMouseDown. Please help!
three.js is mainly for drawing in 3D. If you want to copy a 2D drawing application like paint then using the 2D canvas will probably be easier: canvas.getContext("2d");
.
I will assume that you do want to draw in three.js. In which case I have put together this example. Follow these steps:
Have a look at the code, the main parts are:
You need to project the mouse click coordinates onto the plane. This is done with this function:
function get3dPointZAxis(event)
{
var vector = new THREE.Vector3(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
0.5 );
projector.unprojectVector( vector, camera );
var dir = vector.sub( camera.position ).normalize();
var distance = - camera.position.z / dir.z;
var pos = camera.position.clone().add( dir.multiplyScalar( distance ) );
return pos;
}
Then draw the line from previous to this point:
geometry.vertices.push(lastPoint);
geometry.vertices.push(pos);
var line = new THREE.Line(geometry, material);
scene.add(line);
Note that when you get close to passing through the z plane while rotating, the projection to Z is very far off and you go out of bounds, to prevent this the following check is done:
if( Math.abs(lastPoint.x - pos.x) < 500 && Math.abs(lastPoint.y - pos.y) < 500 && Math.abs(lastPoint.z - pos.z) < 500 )
For reference, I found information for projecting the mouse coordinate here (SO answer) and here (three.js sample).
Update
To draw a line from the mousedown position to the mouseup position see this demo. The code changes are to instead just do the draw between points on mouse up.
function stopDraw(event)
{
if( lastPoint )
{
var pos = get3dPointZAxis(event);
var material = new THREE.LineBasicMaterial({
color: 0x0000ff
});
var geometry = new THREE.Geometry();
if( Math.abs(lastPoint.x - pos.x) < 2000 && Math.abs(lastPoint.y - pos.y) < 2000 && Math.abs(lastPoint.z - pos.z) < 2000 )
{
geometry.vertices.push(lastPoint);
geometry.vertices.push(pos);
var line = new THREE.Line(geometry, material);
scene.add(line);
lastPoint = pos;
}
else
{
console.debug(lastPoint.x.toString() + ':' + lastPoint.y.toString() + ':' + lastPoint.z.toString() + ':' +
pos.x.toString() + ':' + pos.y.toString() + ':' + pos.z.toString());
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With