这里写自定义目录标题
在小程序中引入 Wxml2Canvas 库。
在 wxml 文件中创建需要转换成图片的元素
`
<button @click=“drawMyCanvas”>绘制海报
import Wxml2Canvas from 'wxml2canvas';
export default {
data() {
return {
imgUrl: '',
width: 0,
height: 0
};
},
onLoad() {
},
onReady() {
},
methods: {
drawMyCanvas() {
Taro.showLoading();
const that = this;
const query = Taro.createSelectorQuery().in(this);
query
.select('#my-canvas')
.fields(
{
// 选择需要生成canvas的范围
size: true,
scrollOffset: true
},
data => {
let width = data.width;
let height = data.height;
that.width = width;
that.height = height;
that.startDraw();
}
)
.exec();
},
startDraw() {
console.log(2);
let that = this;
// 创建wxml2canvas对象
let drawMyImage = new Wxml2Canvas(
{
element: 'myCanvas', // canvas的id,
obj: that, // 传入当前组件的this
width: that.width * 2,
height: that.height * 2,
progress(percent) {
// 进度
// console.log(percent);
},
finish(url) {
console.log(url);
// 生成的图片
wx.hideLoading();
that.savePoster(url);
},
error(res) {
// 失败原因
console.log(res);
wx.hideLoading();
}
},
this
);
let data = {
// 获取wxml数据
list: [
{
type: 'wxml',
class: '.my_canvas .my_draw_canvas', // my_canvas要绘制的wxml元素根类名, my_draw_canvas单个元素的类名(所有要绘制的单个元素都要添加该类名)
limit: '.my_canvas', // 要绘制的wxml元素根类名
x: 0,
y: 0
}
]
};
// 绘制canvas
drawMyImage.draw(data, this);
},
savePoster(imgUrl) {
const that = this;
Taro.saveImageToPhotosAlbum({
filePath: imgUrl,
success: function() {
Taro.showToast({
title: '保存成功',
icon: 'none',
duration: 1500
});
},
fail(err) {
if (
err.errMsg === 'saveImageToPhotosAlbum:fail:auth denied' ||
err.errMsg === 'saveImageToPhotosAlbum:fail auth deny' ||
err.errMsg === 'saveImageToPhotosAlbum:fail authorize no response'
) {
Taro.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success: modalSuccess => {
Taro.openSetting({
success(settingdata) {
if (settingdata.authSetting['scope.writePhotosAlbum']) {
Taro.saveImageToPhotosAlbum({
filePath: imgUrl,
success: function() {
Taro.showToast({
title: '保存成功',
icon: 'success',
duration: 2000
});
}
});
} else {
Taro.showToast({
title: '授权失败,请稍后重新获取',
icon: 'none',
duration: 1500
});
}
}
});
}
});
}