首页 > 其他分享 >three demo

three demo

时间:2023-11-21 17:25:35浏览次数:28  
标签:map const demo THREE three window position new

import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import {  CSS2DRenderer,
    CSS2DObject,} from  "three/examples/jsm/renderers/CSS2DRenderer.js";
import * as d3 from 'd3';

const scene = new THREE.Scene();

const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
const ambientLight = new THREE.AmbientLight(0xd4e7fd, 4);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xe8eaeb, 0.2);
directionalLight.position.set(0, 10, 5);
const directionalLight2 = directionalLight.clone();
directionalLight2.position.set(0, 10, -5);
const directionalLight3 = directionalLight.clone();
directionalLight3.position.set(5, 10, 0);
const directionalLight4 = directionalLight.clone();
directionalLight4.position.set(-5, 10, 0);
scene.add(directionalLight);
scene.add(directionalLight2);
scene.add(directionalLight3);
scene.add(directionalLight4);

const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.position.y = 8;
camera.position.z = 8;

const labelRenderer = new CSS2DRenderer();
labelRenderer.domElement.style.position = "absolute";
labelRenderer.domElement.style.top = "0px";
labelRenderer.domElement.style.pointerEvents = "none";
labelRenderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("map").appendChild(labelRenderer.domElement);

const renderer = new THREE.WebGLRenderer({ alpha: true });

renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("map").appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.update();
const animate = () => {
  requestAnimationFrame(animate);
  controls.update();
  renderer.render(scene, camera);
  labelRenderer.render(scene, camera);
};
animate();
window.addEventListener("resize", () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
  labelRenderer.setSize(window.innerWidth, window.innerHeight);
});

// const url = "https://xtjj-1253239320.cos.ap-shanghai.myqcloud.com/330000_full.json";
// fetch(url)
//   .then((res) => res.json())
//   .then((data) => {

//   });
import('./330000_full.json').then(data=>{
// import('./china.json').then(data=>{
    const map = createMap(data);
    scene.add(map);

    let intersect = null;
    window.addEventListener("pointerdown", (event) => {
      const mouse = new THREE.Vector2();
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
      const raycaster = new THREE.Raycaster();
      raycaster.setFromCamera(mouse, camera);
      const intersects = raycaster
        .intersectObjects(map.children)
        .filter((item) => item.object.type !== "Line");
      if (intersects.length > 0) {
        if (intersects[0].object.type === "Mesh") {
          if (intersect) isAplha(intersect, 1);
          intersect = intersects[0].object.parent;
          isAplha(intersect, 0.8);
        }
        if (intersects[0].object.type === "Sprite") {
          console.log(intersects[0].object);
        }
      } else {
        if (intersect) isAplha(intersect, 1);
      }
      function isAplha(intersect, opacity) {
        intersect.children.forEach((item) => {
          if (item.type === "Mesh") {
            item.material.opacity = opacity;
            item.position.z=opacity==1?0:0.5
            // console.log(item.style);
          }
        });
      }
    });
})

const offsetXY = d3.geoMercator();

const createMap = (data) => {
const map = new THREE.Object3D();
const center = data.features[0].properties.centroid;
offsetXY.center(center).translate([0, 0]);
data.features.forEach((feature) => {
  const unit = new THREE.Object3D();
  const { centroid, center, name } = feature.properties;
  const { coordinates, type } = feature.geometry;
  const point = centroid || center || [0, 0];

//   const color = new THREE.Color(`hsl(
//     ${233},
//     ${Math.random() * 30 + 55}%,
//     ${Math.random() * 30 + 55}%)`).getHex();

    const color = new THREE.Color(0x1e80ff)
//   const depth = Math.random() * 0.3 + 0.3;
  const depth = 0.6

  const label = createLabel(name, point, depth);

  const icon = createIcon(center, depth);

  coordinates.forEach((coordinate) => {

    if (type === "MultiPolygon") {
        coordinate.forEach((item) => fn(item));
    }
    else if (type === "Polygon") {
        fn(coordinate);
    }

    function fn(coordinate) {
      unit.name = name;
      const mesh = createMesh(coordinate, color, depth);
      const line = createLine(coordinate, depth);
      unit.add(mesh, ...line);
    }
  });
  if(center){

      map.add(unit, label, icon);
  }else{
    map.add(unit, label);
  }

  setCenter(map);
});
return map;
};
const createMesh = (data, color, depth) => {
const shape = new THREE.Shape();
data.forEach((item, idx) => {
  const [x, y] = offsetXY(item);

  if (idx === 0) shape.moveTo(x, -y);
  else shape.lineTo(x, -y);
});

const extrudeSettings = {
  depth: depth,
  bevelEnabled: false,
};
const materialSettings = {
  color: color,
  emissive: 0x000000,
  roughness: 0.45,
  metalness: 0.8,
  transparent: true,
  side: THREE.DoubleSide,
};
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
const material = new THREE.MeshStandardMaterial(materialSettings);
const mesh = new THREE.Mesh(geometry, material);

return mesh;
};
const createLine = (data, depth) => {
const points = [];
data.forEach((item) => {
  const [x, y] = offsetXY(item);
  points.push(new THREE.Vector3(x, -y, 0));
});
const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
const uplineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff });
const downlineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff });

const upLine = new THREE.Line(lineGeometry, uplineMaterial);
const downLine = new THREE.Line(lineGeometry, downlineMaterial);
downLine.position.z = -0.0001;
upLine.position.z = depth + 0.0001;
return [upLine, downLine];
};
const createLabel = (name, point, depth) => {
const div = document.createElement("div");
div.style.color = "#fff";
div.style.fontSize = "12px";
div.style.textShadow = "1px 1px 2px #047cd6";
div.textContent = name;
const label = new CSS2DObject(div);
label.scale.set(0.01, 0.01, 0.01);
const [x, y] = offsetXY(point);
label.position.set(x, -y, depth);
return label;
};
const createIcon = (point, depth) => {
    if(!point){return}
const url ='https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/img/star.641eec7.png';
const map = new THREE.TextureLoader().load(url);
const material = new THREE.SpriteMaterial({
  map: map,
  transparent: true,
});
const sprite = new THREE.Sprite(material);
const [x, y] = offsetXY(point);
sprite.scale.set(0.3, 0.3, 0.3);

sprite.position.set(x, -y, depth + 0.2);
sprite.renderOrder = 1;

return sprite;
};
const setCenter = (map) => {
map.rotation.x = -Math.PI / 2;
const box = new THREE.Box3().setFromObject(map);
const center = box.getCenter(new THREE.Vector3());

const offset = [0, 0];
map.position.x = map.position.x - center.x - offset[0];
map.position.z = map.position.z - center.z - offset[1];
};



标签:map,const,demo,THREE,three,window,position,new
From: https://www.cnblogs.com/7c89/p/17847041.html

相关文章

  • 设计器demo示例数据库连接不上
    设计器demo示例数据库连接不上首先看下示例的 demo数据库是否启动。启动后可以看下左侧的控制台是否有错误,如果启动后链接还有问题,那么将设计器关闭,然后看下系统进程是否有重新连接。......
  • NOIP 2023 游记 (demo)
    Day0水水水。。APJ把fnaf电影看了。好像和APJ的期望相差比较大。啥时候普及脑机接口啊。看到有人打3,2,1,遂打。打了两天IN一直都是91万左右。。颁奖典礼,膜拜国际特级大师Su_Zipei,今一您扬向。因为和K8He是一个房间的所以就天然面基了crimson000和Tibrella......
  • ThreejsWeb3D开发之可视化大数据地图
    详情课程链接:​​Threejs之数据可视化大屏地图​​简介:从0到1采用Vite去搭建Threejs场景,数据可视化地图效果基本满足,详细解说着色器入门到编写,学习Threejs从基础到进阶操作,带你将Three.js技术落地,掌握其实际应用一、初始化Threejs场景二、超真实度假天空效果二(1)Sky天空效果......
  • 最新demo版|如何0-1开发支付宝小程序之前期准备篇(一)
    小程序作为目前一种轻量、便捷的应用、目前应用越来越广泛了。很多没有开发经验的开发同学可能初次接触就是小程序开发,为了详细讲解下小程序开发的步骤,我会按照小程序的开发流程一步一步从零开始给大家介绍下如何开发支付宝小程序,后续教程中会更新最新版demo给到大家。今天......
  • (倒推2)E:\mmdetection-main\demo\image_demo.py 代码解读
    #Copyright(c)OpenMMLab.Allrightsreserved."""ImageDemo.Thisscriptadoptsanewinfenenceclass,currentlysupportsimagepath,np.arrayandfolderinputformats,andwillsupportvideoandwebcaminthefuture.Example:Save......
  • springcloud教程 -- 快速搭建入门级demo
    废话不多讲,跟紧我,开启你的SpringCloud初体验 首先回顾微服务的基本组成: [图片here] 生产者:提供服务消费者:消费服务服务注册/发现中心:服务注册,发现,监控所以,首先明白springcloud微服务的架构基础:生产者(client),消费者(client),服务注册/发现中心(server) ****************......
  • WebGL_0019:three.js 欧拉角和四元数
    1,这篇说说欧拉角和四元数,欧拉角和四元数的优缺点是老生常谈的话题了,使用条件我就不多说了,我只说一下使用方法。1.欧拉角(Euler)欧拉角描述一个旋转变换,通过指定轴顺序和其各个轴向上的指定旋转角度来旋转一个物体。下面我们开看看它的方法1.set(x:number,y:number,z:......
  • .net6.0及以上WPF中使用GDI+的demo
    usingSystem;usingSystem.Drawing;usingSystem.Runtime.InteropServices;usingSystem.Windows;usingSystem.Windows.Interop;usingSystem.Windows.Media.Imaging;namespaceTryDemo{///<summary>///InteractionlogicforMainWindow.xaml......
  • Three.js BufferGeometry
    BufferGeometry是Three.js最基本的几何体。所有的几何体都继承于BufferGeometry。BufferGeometry的使用。//Sceneconstscene=newTHREE.Scene()constgeometry=newTHREE.BufferGeometry();//createasimplesquareshape.Weduplicatethetopleftandbottomrigh......
  • 基于 three.js 加载器分别加载模型
    点击查看代码/***参数:模型文件路径,成功回调函数**基于three.js加载器分别加载模型**全部加载后通过回调函数传出打印*/import{FBXLoader}from'three/examples/jsm/loaders/FBXLoader.js'import{GLTFLoader}from'three/examples/jsm/loaders/GLTF......