欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用three.js 绘制三维带箭头线的详细过程

程序员文章站 2022-03-20 15:10:50
需求:这个需求是个刚需啊!在一个地铁场景里展示逃生路线,这个路线肯定是要有指示箭头的,为了画这个箭头,我花了不少于十几个小时,总算做出来了,但始终有点问题。我对这个箭头的要求是,无论场景拉近还是拉远,...

需求:这个需求是个刚需啊!在一个地铁场景里展示逃生路线,这个路线肯定是要有指示箭头的,为了画这个箭头,我花了不少于十几个小时,总算做出来了,但始终有点问题。我对这个箭头的要求是,无论场景拉近还是拉远,这个箭头不能太大,也不能太小看不清,形状不能变化,否则就不像箭头了。

使用到了 three.js 的 line2.js 和一个开源库meshline.js

部分代码:

drawpath.js:

/**
 * 绘制路线
 */

import * as three from '../build/three.module.js';
import { meshline, meshlinematerial, meshlineraycast } from '../js.my/meshline.js';

import { line2 } from '../js/lines/line2.js';
import { linematerial } from '../js/lines/linematerial.js';
import { linegeometry } from '../js/lines/linegeometry.js';
import { geometryutils } from '../js/utils/geometryutils.js';

import { canvasdraw } from '../js.my/canvasdraw.js';

import { utils } from '../js.my/utils.js';
import { msg } from '../js.my/msg.js';

let drawpath = function () {

    let _self = this;

    let _canvasdraw = new canvasdraw();
    let utils = new utils();
    let msg = new msg();

    this._isdrawing = false;
    this._path = [];
    this._lines = [];
    this._arrows = [];

    let _depthtest = true;
    let _side = 0;

    let viewercontainerid = '#cc';
    let viewercontainer = $(viewercontainerid)[0];

    let objects;
    let camera;
    let turn;
    let scene;

    this.config = function (objects_, camera_, scene_, turn_) {
        objects = objects_;
        camera = camera_;
        turn = turn_;
        scene = scene_;

        this._olddistance = 1;
        this._oldcamerapos = { x: camera.position.x, y: camera.position.y, z: camera.position.z }
    }

    this.start = function () {
        if (!this._isdrawing) {
            this._isdrawing = true;
            viewercontainer.addeventlistener('click', ray);
            viewercontainer.addeventlistener('mousedown', mousedown);
            viewercontainer.addeventlistener('mouseup', mouseup);
        }
        msg.show("请点击地面画线");
    }

    this.stop = function () {
        if (this._isdrawing) {
            this._isdrawing = false;
            viewercontainer.removeeventlistener('click', ray);
            viewercontainer.addeventlistener('mousedown', mousedown);
            viewercontainer.addeventlistener('mouseup', mouseup);
        }
        msg.show("停止画线");
    }

    function mousedown(params) {
        this._mousedownposition = { x: camera.position.x, y: camera.position.y, z: camera.position.z }
    }

    function mouseup(params) {
        this._mouseupposition = { x: camera.position.x, y: camera.position.y, z: camera.position.z }
    }

    function ray(e) {
        turn.unfocusbutton();

        let raycaster = createraycaster(e.clientx, e.clienty);
        let intersects = raycaster.intersectobjects(objects.all);
        if (intersects.length > 0) {
            let point = intersects[0].point;

            let distance = utils.distance(this._mousedownposition.x, this._mousedownposition.y, this._mousedownposition.z, this._mouseupposition.x, this._mouseupposition.y, this._mouseupposition.z);

            if (distance < 5) {
                _self._path.push({ x: point.x, y: point.y + 50, z: point.z });

                if (_self._path.length > 1) {
                    let point1 = _self._path[_self._path.length - 2];
                    let point2 = _self._path[_self._path.length - 1];

                    drawline(point1, point2);
                    drawarrow(point1, point2);
                }
            }
        }
    }

    function createraycaster(clientx, clienty) {
        let x = (clientx / $(viewercontainerid).width()) * 2 - 1;
        let y = -(clienty / $(viewercontainerid).height()) * 2 + 1;

        let standardvector = new three.vector3(x, y, 0.5);

        let worldvector = standardvector.unproject(camera);

        let ray = worldvector.sub(camera.position).normalize();

        let raycaster = new three.raycaster(camera.position, ray);

        return raycaster;
    }

    this.refresh = function () {
        if (_self._path.length > 1) {
            let distance = utils.distance(this._oldcamerapos.x, this._oldcamerapos.y, this._oldcamerapos.z, camera.position.x, camera.position.y, camera.position.z);
            let ratio = 1;
            if (this._olddistance != 0) {
                ratio = math.abs((this._olddistance - distance) / this._olddistance)
            }

            if (distance > 5 && ratio > 0.1) {
                console.log("======== drawpath 刷新 ====================================================")
                for (let i = 0; i < _self._path.length - 1; i++) {
                    let arrow = _self._arrows[i];
                    let point1 = _self._path[i];
                    let point2 = _self._path[i + 1];
                    refresharrow(point1, point2, arrow);
                }
                this._olddistance = distance;
                this._oldcamerapos = { x: camera.position.x, y: camera.position.y, z: camera.position.z }
            }
        }
    }

    function drawline(point1, point2) {
        const positions = [];

        positions.push(point1.x / 50, point1.y / 50, point1.z / 50);
        positions.push(point2.x / 50, point2.y / 50, point2.z / 50);

        let geometry = new linegeometry();
        geometry.setpositions(positions);

        let matline = new linematerial({
            color: 0x009900,
            linewidth: 0.003, // in world units with size attenuation, pixels otherwise
            dashed: true,
            depthtest: _depthtest,
            side: _side
        });

        let line = new line2(geometry, matline);
        line.computelinedistances();
        line.scale.set(50, 50, 50);

        scene.add(line);
        _self._lines.push(line);

    }

    function drawarrow(point1, point2) {
        let arrowline = _self.createarrowline(point1, point2);
        var meshline = arrowline.meshline;

        let canvastexture = _canvasdraw.drawarrow(three, renderer, 300, 100); //箭头

        var material = new meshlinematerial({
            usemap: true,
            map: canvastexture,
            color: new three.color(0x00f300),
            opacity: 1,
            resolution: new three.vector2($(viewercontainerid).width(), $(viewercontainerid).height()),
            linewidth: arrowline.linewidth,
            depthtest: _depthtest,
            side: _side,
            repeat: new three.vector2(1, 1),
            transparent: true,
            sizeattenuation: 1
        });

        var mesh = new three.mesh(meshline.geometry, material);
        mesh.scale.set(50, 50, 50);
        scene.add(mesh);
        _self._arrows.push(mesh);

    }

    function refresharrow(point1, point2, arrow) {
        let arrowline = _self.createarrowline(point1, point2);
        var meshline = arrowline.meshline;

        let canvastexture = _canvasdraw.drawarrow(three, renderer, 300, 100); //箭头

        var material = new meshlinematerial({
            usemap: true,
            map: canvastexture,
            color: new three.color(0x00f300),
            opacity: 1,
            resolution: new three.vector2($(viewercontainerid).width(), $(viewercontainerid).height()),
            linewidth: arrowline.linewidth,
            depthtest: _depthtest,
            side: _side,
            repeat: new three.vector2(1, 1),
            transparent: true,
            sizeattenuation: 1
        });

        arrow.geometry = meshline.geometry;
        arrow.material = material;

    }

    this.createarrowline = function (point1, point2) {
        let centerpoint = { x: (point1.x + point2.x) / 2, y: (point1.y + point2.y) / 2, z: (point1.z + point2.z) / 2 };
        let distance = utils.distance(point1.x, point1.y, point1.z, point2.x, point2.y, point2.z);

        var startpos = { x: (point1.x + point2.x) / 2 / 50, y: (point1.y + point2.y) / 2 / 50, z: (point1.z + point2.z) / 2 / 50 }

        let d = utils.distance(centerpoint.x, centerpoint.y, centerpoint.z, camera.position.x, camera.position.y, camera.position.z);
        if (d < 2000) d = 2000;
        if (d > 10000) d = 10000;
        let linewidth = 100 * d / 4000;
        //console.log("d=", d);

        let sc = 0.035;
        var endpos = { x: startpos.x + (point2.x - point1.x) * sc * d / distance / 50, y: startpos.y + (point2.y - point1.y) * sc * d / distance / 50, z: startpos.z + (point2.z - point1.z) * sc * d / distance / 50 }

        var arrowlinepoints = [];
        arrowlinepoints.push(startpos.x, startpos.y, startpos.z);
        arrowlinepoints.push(endpos.x, endpos.y, endpos.z);

        var meshline = new meshline();
        meshline.setgeometry(arrowlinepoints);

        return { meshline: meshline, linewidth: linewidth };
    }

    this.setdepthtest = function (bl) {
        if (bl) {
            _depthtest = true;
            this._lines.map(line => {
                line.material.depthtest = true;
                line.material.side = 0;
            });
            this._arrows.map(arrow => {
                arrow.material.depthtest = true;
                arrow.material.side = 0;
            });
        } else {
            _depthtest = false;
            this._lines.map(line => {
                line.material.depthtest = false;
                line.material.side = three.doubleside;
            });
            this._arrows.map(arrow => {
                arrow.material.depthtest = false;
                arrow.material.side = three.doubleside;
            });
        }
    }

    /**
     * 撤销
     */
    this.undo = function () {
        scene.remove(this._lines[this._lines.length - 1]);
        scene.remove(this._arrows[this._arrows.length - 1]);
        _self._path.splice(this._path.length - 1, 1);
        _self._lines.splice(this._lines.length - 1, 1);
        _self._arrows.splice(this._arrows.length - 1, 1);
    }

}

drawpath.prototype.constructor = drawpath;

export { drawpath }

show.js中的部分代码:

let drawpath;

    //绘制线路
    drawpath = new drawpath();
    drawpath.config(
        objects,
        camera,
        scene,
        turn
    );

    $("#rightcontainer").show();
    $("#line-start").on("click", function (event) {
        drawpath.start();
    });
    $("#line-stop").on("click", function (event) {
        drawpath.stop();
    });
    $("#line-undo").on("click", function (event) {
        drawpath.undo();
    });
    $("#line-show").on("click", function (event) {
        drawpath.refresh();
    });
    let depthtest = true;
    $("#line-depthtest").on("click", function (event) {
        if (depthtest) {
            drawpath.setdepthtest(false);
            depthtest = false;
        } else {
            drawpath.setdepthtest(true);
            depthtest = true;
        }
    });

setinterval(() => {
    drawpath && drawpath.refresh();
}, 100);

效果图:

使用three.js 绘制三维带箭头线的详细过程

还是有点问题:

使用three.js 绘制三维带箭头线的详细过程

虽然这个效果图中,场景拉近,箭头有点大,但是最大大小还是做了控制的,就是这个形状有点问题,可能是视角的问题。

我期望的效果应该是这样的,就是无论从什么角度看,箭头不要变形:

使用three.js 绘制三维带箭头线的详细过程

到此这篇关于用 three.js 绘制三维带箭头线要了我半条命的文章就介绍到这了,更多相关three.js 三维带箭头线内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!