Vue中设置preserveDrawingBuffer=true仍无法用html2canvas下载WebGL内容
问题
在Vue项目中尝试使用html2canvas库下载包含HERE MAPS的div内容为图片,即使已在代码中设置preserveDrawingBuffer = true,仍收到“unable to clone WebGL context as it has preserveDrawingBuffer=false”错误。以下是编写的下载函数:
downloadImage() { const scale = 4 // Specify the quality in megapixels const myDiv = this.$refs.hereMap const divCan = document.querySelector('#map canvas') const gl = divCan.getContext('webgl') gl.preserveDrawingBuffer = true const clone = divCan.cloneNode(true) console.log(divCan) const canvas = document.createElement('canvas') canvas.width = myDiv.offsetWidth * scale canvas.height = myDiv.offsetHeight * scale // Create a WebGL context with preserveDrawingBuffer set to true const ctx = canvas.getContext('2d') ctx.scale(scale, scale) html2canvas(myDiv, { canvas: canvas, useCORS: true, logging: true, letterRendering: 1, allowTaint: true, imageTimeout: 0 }) .then(function(canvas) { canvas.toBlob(function(blob) { saveAs(blob, 'my-div-image.png') // Download the image }) }) }
解决方案
- 提前配置HERE Maps的WebGL上下文:WebGL的
preserveDrawingBuffer属性必须在上下文创建时设置才生效,事后修改无法改变原有上下文的行为。因此需要在初始化HERE Maps时,直接开启该配置:
const map = new H.Map( document.getElementById('map'), defaultLayers.vector.normal.map, { // 保留你的其他地图配置 renderingOptions: { preserveDrawingBuffer: true } } );
- 简化html2canvas调用逻辑:无需手动克隆canvas或创建自定义画布,直接让html2canvas处理目标div即可,调整后的下载函数:
downloadImage() { const scale = 4; const myDiv = this.$refs.hereMap; html2canvas(myDiv, { scale: scale, useCORS: true, allowTaint: true, logging: true, imageTimeout: 0 }).then(canvas => { canvas.toBlob(blob => { saveAs(blob, 'my-div-image.png'); }); }); }
内容的提问来源于stack exchange,提问作者Sujith Johnson
相关产品推荐
相关产品推荐

