先上官方项目地址:html2canvas
第一步:html转为canvas
基于html2canvas.js可将一个元素渲染为canvas,只需要简单的调用html2canvas(element[, options])即可。下列html2canvas方法会返回一个包含有<canvas>元素的promise:
html2canvas(document.body).then(function(canvas) {document.body.appendChild(canvas)
})
第二步:canvas转image
上一步生成的canvas即为包含目标元素的<canvas>元素对象。实现保存图片的目标只需要将canvas转image即可。
使用第三方库Canvas2Image.js,调用其convertToImage方法。Canvas2Image.js
下面是一个完整的例子:
convert2canvas() {var shareContent = YourTargetElem
var width = shareContent.offsetWidth
var height = shareContent.offsetHeight
var canvas = document.createElement("canvas")
var scale = 2
canvas.width = width * scale
canvas.height = height * scale
canvas.getContext("2d").scale(scale, scale)
var opts = {
scale: scale,
canvas: canvas,
logging: true,
width: width,
height: height
}
html2canvas(shareContent, opts).then(function (canvas) {
var context = canvas.getContext('2d')
var img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height)
document.body.appendChild(img)
$(img).css({
"width": canvas.width / 2 + "px",
"height": canvas.height / 2 + "px",
})
})
}
1.出现跨域的情况
这种情况只会出现在html2Canvas需生成的海报中的图片与当前环境不在同一个域下
2.解决方案
处理跨域,将接口返回的url处理为base64再进行处理或者后端直接返回base64
3.如何将url转换为base64?(利用canvas的toDataURL属性将url转为base64)
function getImageBase64Data(imgSrc) {
function getBase64(img) {
let canvas = document.createElement("canvas")
canvas.width = img.width
canvas.height = img.height
let ctx = canvas.getContext("2d")
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
let dataURL = canvas.toDataURL('image/jpeg')
return dataURL
}
let baseUrl = new Promise(function (resolve, reject) {
let image = new Image()
image.crossOrigin = '*'// 图片处理跨域
if (imgSrc.indexOf('data:image/jpegbase64') >-1) {
image.src = imgSrc + '?v=' + Math.random()// 处理图片从缓存获取
} else {
image.src = imgSrc
}
image.onload = function () {
let imageBase64Data = getBase64(image)
resolve(imageBase64Data)
}
})
return baseUrl
}
4.使用html2Canvas生成海报
const download = () => {
let content = document.getElementById('promote-content')
if (content) {
html2canvas(content, { useCORS: true, allowTaint: true }).then(res => {
const imgBase64 = res.toDataURL('image/jpeg')
let link = document.createElement('a')
link.style.display = 'none'
link.href = imgBase64
link.setAttribute('download', name + moment().format('YYYYMMDDHHmm'))
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
}
}