使用CanvasRenderingContext2D.drawImage()拼接截图

概述:Canvas 2D API 的 CanvasRenderingContext2D.drawImage() 方法提供了多种在画布(Canvas)上绘制图像的方式。

前景提示:接到一个需求在argis地图上截图并下载到本地;本身是一个很普通的需求,但是arcgis支持的截图只能截取到地图,地图上的图例或者其他的东西都不能截取;so,就换成html2canvs 截图工具但是,html2canvs只能截取非地图的部分!于是就想到了这个办法:拿到两张图拼接到一起!!

主要用到:

argis:takeScreenshot()

html2canvs

CanvasRenderingContext2D.drawImage()

下面是主要代码:

javascript 复制代码
import html2canvas from 'html2canvas'


async function combineMapAndLegend (mapView: __esri.View) {
  const mapData = await captureMap(mapView)
  const legendCanvas = await captureLegend()

  const finalCanvas = document.createElement('canvas')
  const finalCtx = finalCanvas.getContext('2d')
  const mapImage = new Image()
  mapImage.src = mapData.dataUrl
  await new Promise((resolve) => {
    mapImage.onload = resolve
  })
  finalCanvas.width = mapImage.width
  finalCanvas.height = mapImage.height
  // 绘制地图截图
  finalCtx.drawImage(mapImage, 0, 0)
  // 计算图例在右下角的位置 并留点边距10
  const legendX = mapImage.width - (legendCanvas.width / 2 + 10)
  const legendY = mapImage.height - (legendCanvas.height / 2 + 10)
  const dWidth = legendCanvas.width / 2
  const dHeight = legendCanvas.height / 2
  // 绘制图例
  finalCtx.drawImage(legendCanvas, legendX, legendY, dWidth, dHeight)
  finalCanvas.toBlob((blob) => {
    if (blob) {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '地图截图.png'
      a.click()
      URL.revokeObjectURL(url)
    }
  })
  return finalCanvas
}

async function captureMap (mapView: __esri.View) {
  try {
    const res = await mapView.takeScreenshot()
    return res
  }
  catch (error) {
    console.error('截图失败:', error)
  }
}

async function captureLegend () {
  let legendRef = document.querySelector('.legend-wrap')
  if (!legendRef) {
    legendRef = document.querySelector('.esri-legend')
  }
  try {
    const canvas = await html2canvas(legendRef, {
      backgroundColor: null,
      scale: 2,
    })
    return canvas
  }
  catch (error) {
    console.error('截图失败:', error)
  }
}

export default  combineMapAndLegend
相关推荐
webkubor1 天前
🧠 2025:AI 写代码越来越强,但我的项目返工却更多了
前端·机器学习·ai编程
Sun_小杰杰哇1 天前
Dayjs常用操作使用
开发语言·前端·javascript·typescript·vue·reactjs·anti-design-vue
戴维南1 天前
TypeScript 在项目中的实际解决的问题
前端
晴殇i1 天前
package.json 中的 dependencies 与 devDependencies:深度解析
前端·设计模式·前端框架
basestone1 天前
🚀 从重复 CRUD 到工程化封装:我是如何设计 useTableList 统一列表逻辑的
javascript·react.js·ant design
pas1361 天前
25-mini-vue fragment & Text
前端·javascript·vue.js
何贤1 天前
2025 年终回顾:25 岁,从“混吃等死”到别人眼中的“技术专家”
前端·程序员·年终总结
软件开发技术深度爱好者1 天前
JavaScript的p5.js库使用介绍
javascript·html
冴羽1 天前
CSS 新特性!瀑布流布局的终极解决方案
前端·javascript·css
满天星辰1 天前
Vue 响应式原理深度解析
前端·vue.js