概述: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