合成图片
Jonnzer Lv4
应用场景
H5的分享海报,需要从后台获取数据,绘制DOM,并且可以长按保存。也就是要求所有DOM都要转为image元素。
需要引用的库
html2Canvas: Screenshots with JavaScript 等于是用js去转换指定的DOM成为image。
需要注意的地方
html2Canvas执行渲染时 ,需等待DOM本身获取后台数据的渲染完成。否则会出现黑背景
示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(window).load(function() {
setTimeout(function () { // 关键在这里,延时进行html2Canvas操作
drawCanvas('#sharePoster_bg_img').then(canvas => {
const img = new Image();
img.style.display = "block";
// 将 canvas 导出成 base64
img.src = canvas.toDataURL('image/jpeg', 0.92);
img.crossOrigin = "Anonymous";
// 添加图片到预览
$('#sharePoster_bg_img').html(img); // 生成的base64图片填充到dom里
$('.save_text').show();
})
},500)
});

优化细节 以及 要用到的工具函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 根据像素比绘制canvas,使生成图片更加高清。
* @param DomSelector
* @returns html2Canvas
**/
async function drawCanvas(selector) {
// 获取想要转换的 DOM 节点
const dom = document.querySelector(selector);
const box = window.getComputedStyle(dom);
// DOM 节点计算后宽高
const width = parseValue(box.width);
const height = parseValue(box.height);
// 获取像素比
const scaleBy = DPR();
// 创建自定义 canvas 元素
const canvas = document.createElement('canvas');

// 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 设定 canvas css宽高为 DOM 节点宽高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 获取画笔
const context = canvas.getContext('2d');

// 将所有绘制内容放大像素比倍
context.scale(scaleBy, scaleBy);

// 将自定义 canvas 作为配置项传入,开始绘制
return await html2canvas(dom, {canvas,
allowTaint: false,
useCORS: true,
async: false,
width: width,
height: height
});
}
1
2
3
4
5
6
7
8
9
10
11
/**
* 根据window.devicePixelRatio获取像素比
* @returns 像素比
*/
function DPR() {
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}

1
2
3
4
5
6
7
8
/**
* 将传入值转为整数
* @param value
* @returns {number}
*/
function parseValue(value) {
return parseInt(value, 10);
}
注意细节:
需绘制的DOM所用到的css属性值最好不用最新的属性,html2Canvas不支持最新的css属性解析,会造成生成的图片有黑色背景。
参考链接:

html2Canvas官网
js资源

  • 本文标题:合成图片
  • 本文作者:Jonnzer
  • 创建时间:2019-02-15 17:32:27
  • 本文链接:https://jonnzer.github.io/2019/02/15/合成图片/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论