当前位置: 首页 > news >正文

基于geojson-vt和canvas的高性能出图

概述

本文介绍基于geojson-vtcanvas,实现node端高性能出图。

效果

动画.gif

性能

实现

1. canvas绘图

import { createCanvas } from 'canvas'const tileSize = 256;
const canvas = createCanvas(tileSize, tileSize)
const ctx = canvas.getContext('2d')

2. 处理geojson

const geojson = result.rows[0].geojson;
geojson.features = geojson.features || []
const tileIndex = geojsonvt(geojson, {maxZoom: 22,tolerance: 3, // simplification tolerance (higher means simpler)extent: 4096, // tile extent (both width and height)buffer: 64,   // tile buffer on each sidedebug: 0,     // logging level (0 to disable, 1 or 2)lineMetrics: false, // whether to enable line metrics tracking for LineString/MultiLineString featurespromoteId: null,    // name of a feature property to promote to feature.id. Cannot be used with `generateId`generateId: false,  // whether to generate feature ids. Cannot be used with `promoteId`indexMaxZoom: 5,       // max zoom in the initial tile indexindexMaxPoints: 100000 // max number of points per tile in the index
})
const features = tileIndex.getTile(Number(z), Number(x), Number(y))?.features || [];

3. 绘制features

function drawTile(features, zoom) {ctx.clearRect(0, 0, tileSize, tileSize);// 绘制边框// ctx.strokeStyle = '#fff'// ctx.lineWidth = 1// ctx.strokeRect(0, 0, tileSize, tileSize)for (let i = 0; i < features.length; i++) {const feature = features[i];const {adcode, name} = feature.tagsconst type = feature.type;ctx.beginPath();for (let j = 0; j < feature.geometry.length; j++) {const geom = feature.geometry[j];if (type === 1) { // 1点ctx.save()ctx.fillStyle = `rgba(${'255,0,0'}, 1)`;ctx.strokeStyle = '#fff'ctx.lineWidth = 2;ctx.textAlign = "center";ctx.textBaseline = "middle"ctx.font = "bold 16px 宋体";// const len = ctx.measureText(name).width / 2;// const offset = 5// if(x + len > tileSize) x = tileSize - len - offset// if(x - len < 0 ) x = len + offsetif(name && zoom >= 9) {ctx.strokeText(name, geom[0] / 16.0, geom[1] / 16.0)ctx.fillText(name, geom[0] / 16.0, geom[1] / 16.0)}// ctx.arc(geom[0] / 16.0, geom[1] / 16.0, 3, 0, 2 * Math.PI, false);ctx.restore()ctx.fill()ctx.stroke()} else { // 2线 或 3面// const color = colorDict[adcode] || '255,0,0'const color = '255,0,0'ctx.strokeStyle = `rgba(${color}, 1)`;ctx.fillStyle = `rgba(${color}, 0.1)`;ctx.lineWidth = 1;for (let k = 0; k < geom.length; k++) {const p = geom[k];if (k) ctx.lineTo(p[0] / 16.0, p[1] / 16.0);else ctx.moveTo(p[0] / 16.0, p[1] / 16.0);}// if (type === 3) ctx.fill();ctx.stroke();}}}
}

4. 设置缓存并发送到前端

app.get('/tile/:z/:x/:y', (req, res) => {const {z, x, y} = req.paramstry {getFeatures(x, y, z).then(image => {res.setHeader('Expires', new Date(Date.now() + 30 * 1000).toUTCString())res.writeHead(200, {"Content-Type": "image/png",});res.end(image);})} catch (err) {console.error(err);}   
})

5. 数据获取

数据是存在PG数据库中,可通过node连接获取,可通过如下语句直接将结果转换为geojson。

SELECT json_build_object('type', 'FeatureCollection','features', json_agg(ST_AsGeoJSON(t.*)::json)
) as geojson FROM (select adcode, name, geom from base_county where st_intersects(BBox(101, 52, 7), geom)
) as t(adcode, name, geom);

image.png

6. 前端调用

new ol.layer.Tile({source: new ol.source.XYZ({url: 'http://127.0.0.1:18089/tile/{z}/{x}/{y}'})
}),
http://www.lryc.cn/news/198474.html

相关文章:

  • CTF是黑客大赛?新手如何入门CTF?
  • 电脑开不了机用U盘重装系统Win10教程
  • 四叉堆在GO中的应用-定时任务timer
  • Flow深入浅出系列之使用Kotlin Flow自动刷新Android数据的策略
  • AC修炼计划(AtCoder Regular Contest 165)
  • 【Express】登录鉴权 JWT
  • 【微服务 SpringCloud】实用篇 · Ribbon负载均衡
  • zabbix-proxy代理服务器配置
  • 【python零基础入门学习】python进阶篇之OOP - 面向对象的程序设计
  • 中国xx集团信息技术工程师面试
  • Jmeter接口自动化测试 —— Jmeter下载安装及入门
  • ARM 学习笔记2 初识Cortex-M33与STM32G4
  • vue中使用coordtransform 互相转换坐标系
  • 双线性插值详解
  • C++ “”
  • 计算机三级有必要考吗?计算机三级有哪些科目?
  • 6.5 Elasticsearch(五)Spring Data Elasticsearch - 增删改查API
  • XPS—专项文献阅读-科学指南针
  • 电脑办公助手之桌面便签,助力高效率办公
  • 【面试题】2023虹软计算机视觉一面
  • 板带纠偏控制系统伺服比例阀放大器
  • 视频I420裸流保存为文件
  • IDEA中SpringBoot项目的yml多环境配置
  • 【Linux】UDP协议
  • AutoCAD 2022 for Mac/Windows升级您的设计工具,提升工作效率
  • 协程,GIL全局解释器,互斥锁,线程池,Concurrent模块
  • MAPEFFECT代码在传奇中有何作用如何运用
  • Godot 官方2D C#重构(1):雪花碰撞
  • 计算机基础知识35
  • VulnHub mrRobot