You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 23:25:18