使用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
相关推荐
fruge11 分钟前
前端自动化脚本:用 Node.js 写批量处理工具(图片压缩、文件重命名)
前端·node.js·自动化
Jolyne_26 分钟前
antd Image base64缓存 + loading 态优化方案
前端
BINGCHN32 分钟前
NSSCTF每日一练 SWPUCTF2021 include--web
android·前端·android studio
O***p60434 分钟前
JavaScript在Node.js中的集群负载均衡
javascript·node.js·负载均衡
Z***u6591 小时前
前端性能测试实践
前端
xhxxx1 小时前
prototype 是遗产,proto 是族谱:一文吃透 JS 原型链
前端·javascript
倾墨1 小时前
Bytebot源码学习
前端
用户93816912553601 小时前
VUE3项目--集成Sass
前端
S***H2831 小时前
Vue语音识别案例
前端·vue.js·语音识别
啦啦9118862 小时前
【版本更新】Edge 浏览器 v142.0.3595.94 绿色增强版+官方安装包
前端·edge