【发布时间】:2014-05-21 10:05:31
【问题描述】:
我是 Three.js 的新手,我正在尝试实现 Microsoft Paint 中用于绘制线段的技术。我正在尝试获取点 onMouseDown 的坐标,然后用 onMouseMove 延伸一条线,直到 onMouseDown。请帮忙!
【问题讨论】:
标签: javascript three.js
我是 Three.js 的新手,我正在尝试实现 Microsoft Paint 中用于绘制线段的技术。我正在尝试获取点 onMouseDown 的坐标,然后用 onMouseMove 延伸一条线,直到 onMouseDown。请帮忙!
【问题讨论】:
标签: javascript three.js
three.js 主要用于 3D 绘图。如果您想复制像绘画这样的 2D 绘图应用程序,那么使用 2D 画布可能会更容易:canvas.getContext("2d");。
我假设您确实想在three.js 中进行绘制。在这种情况下,我将 this example 放在一起。请按以下步骤操作:
看一下代码,主要部分是:
您需要将鼠标点击坐标投影到平面上。这是通过这个函数完成的:
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;
}
然后从前一个点画线:
geometry.vertices.push(lastPoint);
geometry.vertices.push(pos);
var line = new THREE.Line(geometry, material);
scene.add(line);
请注意,当您在旋转时接近通过 z 平面时,到 Z 的投影距离很远,您会超出界限,为防止这种情况发生,请执行以下检查:
if( Math.abs(lastPoint.x - pos.x) < 500 && Math.abs(lastPoint.y - pos.y) < 500 && Math.abs(lastPoint.z - pos.z) < 500 )
作为参考,我找到了有关投影鼠标坐标here(SO 答案)和here(three.js 示例)的信息。
更新
要从 mousedown 位置到 mouseup 位置画一条线,请参阅 this demo。代码更改是改为只在鼠标向上的点之间进行绘制。
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());
}
}
}
【讨论】:
canvas.getContext("2d"); 和LineTo。请参阅html5canvastutorials.com/tutorials/html5-canvas-lines 和 html5canvastutorials.com/tutorials/html5-canvas-line-caps 和 tutorialspoint.com/html5/canvas_drawing_lines.htm。