Word加载项(Office.js)中OpenLayers导出地图base64插入文档失败
Word加载项集成OpenLayers插入地图功能异常问题
需求与实现思路
- 核心目标:基于Office.js开发Word加载项,集成OpenLayers地图能力,实现向Word文档插入地图的功能
- 参考OpenLayers官方地图导出示例设计的标准流程共3步:
- 初始化生成OpenLayers地图实例
- 将完成渲染的地图转换为base64格式图片
- 调用Word JS API将转换后的图片插入文档
- 调试安排:原计划最终将该功能部署在
command.ts文件中,由于无UI的后台部分调试难度较高,先在task.ts中完成开发调试,方便观测底层运行逻辑。
已完成的功能验证
地图初始化模块
编写的地图初始化函数如下:
function initMap() { return new Map({ target: "map", layers: [ new TileLayer({ source: new OSM(), }), ], view: new View({ center: fromLonLat([7.0785, 51.4614]), zoom: 4, }), }); }
- 在
task.html页面放置了id为map的div容器作为地图挂载点,点击页面按钮触发initMap()调用时,地图可正常在该div中完成渲染,该步骤无运行异常。
图片导出模块
参考OpenLayers官方导出示例编写了地图转base64图片的逻辑,该段代码在普通HTML页面中测试可正常运行,但迁移到Word加载项环境后运行异常,代码如下:
let map = initMap(); var dataURL = ""; const mapCanvas = document.createElement("canvas"); const size = map.getSize(); mapCanvas.width = size[0]; mapCanvas.height = size[1]; const mapContext = mapCanvas.getContext("2d"); console.log("Get Canvas"); //console.log(map.getViewport().innerHTML); Array.prototype.forEach.call( map.getViewport().querySelectorAll(".ol-layer canvas, canvas.ol-layer"), (canvas) => { console.log(canvas.height); if (canvas.width > 0) { const opacity = canvas.parentNode.style.opacity || canvas.style.opacity; // mapContext.globalAlpha = opacity === "" ? 1 : Number(opacity); const backgroundColor = canvas.parentNode.style.backgroundColor; if (backgroundColor) { mapContext.fillStyle = backgroundColor; mapContext.fillRect(0, 0, canvas.width, canvas.height); } let matrix; const transform = canvas.style.transform; const transformMatch = transform.match(/^matrix\(([^(]*)\)$/); if (transformMatch && transformMatch.length > 1) { // 从样式的变换矩阵中提取变换参数,应用到导出画布上下文 const matrix = transformMatch[1].split(",").map(Number); mapContext.setTransform(...matrix); } mapContext.drawImage(canvas, 0, 0); } } ); mapContext.globalCompositeOperation = "destination-over"; mapContext.fillStyle = "white"; mapContext.fillRect(0, 0, mapCanvas.width, mapCanvas.height); mapContext.globalAlpha = 1; dataURL = mapCanvas.toDataURL("image/png", 1); var base64Image = dataURL.replace("data:image/png;base64,", "");
具体异常现象
通过MS Edge Developer Tools监控运行过程,可观测到以下现象:
- 地图本身已正常生成,DOM结构中存在class为
ol-layer的div,其内部包含canvas渲染元素,OpenLayers生成的完整图层结构可被开发者工具识别 - 执行
map.getViewport().querySelectorAll(".ol-layer canvas, canvas.ol-layer")逻辑时,无法检索到ol-layer对应的div及内部canvas元素:- 添加
console.log(canvas.width)调试语句无任何输出 - 打印选择器匹配到的元素长度返回值为0
- 调用
map.getViewport().innerHTML时仅能返回部分生成的div结构,缺失ol-layer div及对应的canvas元素(经判断这些缺失元素为class为ol-unselectable ol-layers的div的子节点)
- 添加
- 最终生成的base64字符串仅对应纯白色背景图片,不包含任何地图图层内容,无法通过Word JS API的
var image = body.insertInlinePictureFromBase64(base64Image, Word.InsertLocation.start)方法插入有效地图图片,需排查该问题的解决方案。
内容的提问来源于stack exchange,提问作者Stephan
相关产品推荐
相关产品推荐

