本文主要是介绍使用planetaryjs插件实现3维地球仪效果,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、插件下载
npm install planetaryjs -S
二、插件使用
//index.js文件
import * as planetaryjs from 'planetary.js' //引入planetaryjs插件
import fileJson from './data/world.json' //这个json包含了一些地球的信息,我这里单独保存在本地了//渲染地球仪showEarth=()=>{var globe = planetaryjs.planet(); // 创建一个globe对象globe.loadPlugin(autorotate(20)); // 自转速度globe.loadPlugin(planetaryjs.plugins.earth({ //添加地球插件topojson: { file: fileJson},oceans: { fill:'rgba(190,190,190,0.5)'},land: { fill:'#FFFAFA'},borders: { stroke:'#FFFAFA'}}));globe.loadPlugin(planetaryjs.plugins.pings()); // 添加地球上的动态标记点(用于展示)//配置鼠标或触控板的放大缩小globe.loadPlugin(planetaryjs.plugins.zoom({scaleExtent: [100, 300]}));//配置是否允许拖拽globe.loadPlugin(planetaryjs.plugins.drag({onDragStart: function() {this.plugins.autorotate.pause();},onDragEnd: function() {this.plugins.autorotate.resume();}}));//修改地球仪的展示大小、偏移量等 globe.projection.scale(240).translate([300, 300]).rotate([0, -10, 0]);//定时添加动态pings点setInterval(function() {var lat = Math.random() * 170 - 85;var lng = Math.random() * 360 - 180globe.plugins.pings.add(lng, lat, { color: "red", ttl: 2000, angle: 2 });}, 50);var canvas = document.getElementById('rotatingGlobe');globe.draw(canvas);// 旋转角度函数配置function autorotate(degPerSec) {return function(planet) {var lastTick = null;var paused = false;planet.plugins.autorotate = {pause: function() { paused = true; },resume: function() { paused = false; }};planet.onDraw(function() {if (paused || !lastTick) {lastTick = new Date();} else {var now = new Date();var delta = now - lastTick;var rotation = planet.projection.rotate();rotation[0] += degPerSec * delta / 1000;if (rotation[0] >= 180) rotation[0] -= 360;planet.projection.rotate(rotation);lastTick = now;}});};};}
三、world.json文件获取
- 方式1:你可以直接通过调用接口获取:http://planetaryjs.com/world-110m-withlakes.json,该方式有可能会跨域,所以你要处理下跨域问题才能正常得到数据
- 方式2:直接本地保存一份,但这种方式需要对planetary.js原代码进行一些改动,改动如下:
//把源代码中的这部分代码改为如下所示planet.onInit(function(done) {if (config.world) {planet.plugins.topojson.world = config.world;setTimeout(done, 0);} else {var file = config.file || 'world-110m.json';console.log('file',file);planet.plugins.topojson.world = file;done();// d3.json(file, function(err, world) {// if (err) {// throw new Error("Could not load JSON " + file);// }// planet.plugins.topojson.world = world;// done();// });}});
四、最终效果展示
这篇关于使用planetaryjs插件实现3维地球仪效果的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!