黄何裕
2024-07-16 bfb10b42c5fb6bc9f751f88f9351bfc19c6380a4
src/views/screen/components/screen-map-three/experience/world/map.js
@@ -1,17 +1,67 @@
import * as THREE from 'three';
import * as d3 from 'd3';
import mapData from '@/assets/map/zigong.json';
import mapData from '@/assets/map/zigong2.json';
import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer';
import textureMapImage from '@/assets/map/texture/gz-map.jpg';
import textureMapFxImage from '@/assets/map/texture/gz-map-fx.jpg';
import gsap from 'gsap';
// 地图深度
const MAP_DEPTH = 0.2;
const projection = d3.geoMercator().center([104.779307, 29.33924]).translate([0, 0, 0]);
const raycaster = new THREE.Raycaster();
export default class Map {
    constructor(experience) {
        this.experience = experience;
        this.scene = this.experience.scene;
        this.scene = experience.scene;
        this.camera = experience.camera;
        this.provinceMeshList = [];
        this.labelList = [];
        this.textureLoader = new THREE.TextureLoader();
        this.setTexture();
        this.operationData(mapData);
        setTimeout(() => {
            this.enterAnimation();
        }, 500);
    }
    setTexture() {
        const textureMap = this.textureLoader.load(textureMapImage);
        const textureMapFx = this.textureLoader.load(textureMapFxImage);
        textureMap.wrapS = textureMapFx.wrapS = THREE.RepeatWrapping;
        textureMap.wrapT = textureMapFx.wrapT = THREE.RepeatWrapping;
        textureMap.flipY = textureMapFx.flipY = false;
        textureMap.rotation = textureMapFx.rotation = THREE.MathUtils.degToRad(45);
        const scale = 0.128;
        textureMap.repeat.set(scale, scale);
        textureMapFx.repeat.set(scale, scale);
        this.topFaceMaterial = new THREE.MeshPhongMaterial({
            map: textureMap,
            // color: 0xb4eeea,
            color: 0xb3fffa,
            combine: THREE.MultiplyOperation,
            transparent: true,
            opacity: 1,
        });
        this.sideMaterial = new THREE.MeshLambertMaterial({
            color: 0x123024,
            transparent: true,
            opacity: 0.9,
        });
    }
    /**
     * 解析json数据,并绘制地图多边形
     * @param {*} jsondata 地图数据
     */
    operationData(jsondata) {
        this.map = new THREE.Object3D();
        this.map = new THREE.Group();
        // geo信息
        const features = jsondata.features;
        features.forEach((feature) => {
@@ -19,34 +69,49 @@
            const province = new THREE.Object3D();
            // 地址
            province.properties = feature.properties.name;
            const coordinates = feature.geometry.coordinates;
            province.isHover = false;
            // 多个情况
            // console.log(feature.geometry.type);
            if (feature.geometry.type === "MultiPolygon") {
                coordinates.forEach((coordinate) => {
                feature.geometry.coordinates.forEach((coordinate) => {
                    coordinate.forEach((rows) => {
                        const line = this.drawBoundary(rows);
                        const mesh = this.drawExtrudeMesh(rows);
                        province.add(line);
                        province.add(mesh);
                        this.provinceMeshList.push(mesh);
                    });
                });
            }
            // 单个情况
            if (feature.geometry.type === "Polygon") {
                coordinates.forEach((coordinate) => {
                feature.geometry.coordinates.forEach((coordinate) => {
                    const line = this.drawBoundary(coordinate);
                    const mesh = this.drawExtrudeMesh(coordinate);
                    province.add(line);
                    province.add(mesh);
                    this.provinceMeshList.push(mesh);
                });
            }
            const label = this.drawLabelText(feature);
            this.labelList.push({ name: feature.properties.name, label });
            province.add(label);
            this.map.add(province);
            this.map.position.set(0, 0, 0);
        });
        this.map.position.set(1, 1, -1.5);
        this.map.scale.set(10, 10, 1);
        this.map.rotation.set(THREE.MathUtils.degToRad(-90), 0, THREE.MathUtils.degToRad(20));
        this.scene.add(this.map);
        this.setMouseEvent();
    }
    /**
     * 画区域分界线
     * @param {*} polygon 区域坐标点数组
     * @returns 区域分界线
     */
    drawBoundary(polygon) {
        const points = [];
        for (let i = 0; i < polygon.length; i++) {
@@ -55,36 +120,196 @@
        }
        const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
        const lineMaterial = new THREE.LineBasicMaterial({
            color: 'yellow'
            color: 0xffffff,
            linewidth: 2,
            transparent: true,
            depthTest: false,
        });
        return new THREE.Line(lineGeometry, lineMaterial);
        const line = new THREE.Line(lineGeometry, lineMaterial);
        line.translateZ(MAP_DEPTH + 0.001);
        return line;
    }
    /**
     * 绘制区域多边形
     * @param {*} polygon 区域坐标点数组
     * @returns 区域多边形
     */
    drawExtrudeMesh(polygon) {
        const shape = new THREE.Shape();
        for (let i = 0; i < polygon.length; i++) {
            const [x, y] = projection(polygon[i]);
            if (i === 0) {
                shape.moveTo(x, -y);
            }
            shape.lineTo(x, -y);
        }
        const geometry = new THREE.ExtrudeGeometry(shape, {
            depth: 0,
            bevelEnabled: false
            depth: MAP_DEPTH,
            bevelEnabled: false,
            bevelSegments: 1,
            bevelThickness: 0.1,
        });
        return new THREE.Mesh(geometry, [
            this.topFaceMaterial,
            this.sideMaterial,
        ]);
    }
        const material = new THREE.MeshBasicMaterial({
            color: '#fff',
            transparent: true,
            opacity: 0.2,
    drawLabelText(province) {
        const [x, y] = projection(province.properties.center);
        const div = document.createElement('div');
        div.innerHTML = province.properties.name;
        div.style.padding = '4px 10px';
        div.style.color = '#fff';
        div.style.fontSize = '16px';
        div.style.position = 'absolute';
        div.style.backgroundColor = 'rgba(25,25,25,0.5)';
        div.style.borderRadius = '5px';
        const label = new CSS2DObject(div);
        div.style.pointerEvents = 'none';
        label.position.set(x, y, MAP_DEPTH + 0.05);
        return label;
    }
    setMouseEvent() {
        this.mouseEvent = this.handleEvent.bind(this);
        this.experience.canvas.addEventListener("mousemove", this.mouseEvent);
    }
    removeMouseEvent() {
        this.experience.canvas.removeEventListener("mousemove", this.mouseEvent);
    }
    handleEvent(e) {
        // console.log(this);
        // return;
        if (this.map) {
            let mouse = new THREE.Vector2();
            let getBoundingClientRect = this.experience.canvas.getBoundingClientRect();
            let x = ((e.clientX - getBoundingClientRect.left) / getBoundingClientRect.width) * 2 - 1;
            let y = -((e.clientY - getBoundingClientRect.top) / getBoundingClientRect.height) * 2 + 1;
            mouse.x = x;
            mouse.y = y;
            raycaster.setFromCamera(mouse, this.camera.instance);
            let intersects = raycaster.intersectObjects(this.provinceMeshList, false);
            if (intersects.length) {
                let temp = intersects[0].object;
                this.animation(temp.parent);
                this.showLabel(temp.parent);
            } else {
                this.animation();
            }
        }
    }
    throttle(callback, delay) {
        let lastCall = 0;
        return function () {
            let now = new Date().getTime();
            if (now - lastCall >= delay) {
                lastCall = now;
                callback.apply(null, arguments);
            }
        };
    }
    animation(province) {
        if (province) {
            if (!province.isHover) {
                province.isHover = true;
                this.map.children.forEach((item) => {
                    if (item.properties === province.properties) {
                        gsap.to(province.position, {
                            z: 0.12,
                            duration: 0.6
                        })
                    } else {
                        this.resetAnimation(item);
                    }
                })
            }
        } else {
            this.resetAllAnimation();
        }
    }
    resetAnimation(province) {
        gsap.to(province.position, {
            z: 0,
            duration: 0.6,
            onComplete: () => {
                province.isHover = false;
            }
        })
    }
        return new THREE.Mesh(geometry, material);
    resetAllAnimation() {
        this.map.children.forEach((item) => {
            this.resetAnimation(item);
        })
    }
    showLabel(province) {
        this.labelList.forEach((item) => {
            // if (item.name === province.properties) {
            //     item.label.element.style.visibility = 'visible';
            // } else {
            //     item.label.element.style.visibility = 'hidden';
            // }
        })
    }
    enterAnimation() {
        gsap.to(this.map.scale, {
            z: 10,
            duration: 0.6,
            ease: 'power1.out'
        })
    }
    destroy() {
        this.removeMouseEvent();
        this.disposeObject();
        this.removeObject();
        this.resetObject();
    }
    disposeObject() {
        this.map.traverse((child) => {
            if (child.material) {
                // 可能存在材质为数组的情况
                if (child.material instanceof Array) {
                    child.material.forEach((item) => item.dispose());
                } else {
                    child.material.dispose();
                    if (child.material.map) {
                        child.material.map.dispose();
                    }
                }
            }
            if (child.geometry) {
                child.geometry.dispose();
                child.geometry.attributes = null; // 这些属性包括position, normal, uv等等
            }
            child = null;
        });
        this.topFaceMaterial.dispose();
        this.sideMaterial.dispose();
    }
    removeObject() {
        this.scene.remove(this.map);
    }
    resetObject() {
        this.map = null;
        this.provinceMeshList = null;
        this.labelList = null;
        this.textureLoader = null;
    }
}