微信小程序HTML转为Canvas并保存图片

2,066 阅读2分钟

在小程序中,可以使用 Wxml2Canvas 库将 HTML 元素转化为 Canvas 对象,再利用 Canvas 对象将图片保存下来。具体实现流程如下:

  1. 在小程序中引入 Wxml2Canvas 库。
  2. wxml 文件中创建需要转换成图片的元素和一个按钮,例如:
<template>
	<view class="">
		<canvas canvas-id="myCanvas" class="myCanvas"></canvas>
		<view id="my-canvas" class="my_canvas">
			<view class="my_draw_canvas bg">
				<text class="title my_draw_canvas" data-type="text" :data-text="title">1111111111111111111</text>
			</view>
		</view>
		<button @click="drawMyCanvas">保存图片</button>
	</view>
</template>
  1. 在页面的 js 文件中,
import Wxml2Canvas from 'wxml2canvas';
export default {
	data() {
		return {
			title: '1111111111111',
			title1: '22222222222',
			title2: '333',
			title3: '444444444444444444',
			imgUrl: '',
			width: 0,
			height: 0
		};
	},
	onLoad() {},
	onReady() {},
	methods: {
		drawMyCanvas() {
			wx.showLoading();
			const that = this;
			const query = wx.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;
						setTimeout(() => {
							that.startDraw();
						}, 1500);
					}
				)
				.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) {
			console.log(3, imgUrl);
			const that = this;
			wx.saveImageToPhotosAlbum({
				filePath: imgUrl,
				success: function() {
					wx.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'
					) {
						wx.showModal({
							title: '提示',
							content: '需要您授权保存相册',
							showCancel: false,
							success: modalSuccess => {
								wx.openSetting({
									success(settingdata) {
										if (settingdata.authSetting['scope.writePhotosAlbum']) {
											wx.saveImageToPhotosAlbum({
												filePath: imgUrl,
												success: function() {
													wx.showToast({
														title: '保存成功',
														icon: 'success',
														duration: 2000
													});
												}
											});
										} else {
											wx.showToast({
												title: '授权失败,请稍后重新获取',
												icon: 'none',
												duration: 1500
											});
										}
									}
								});
							}
						});
					}
				}
			});
		}
	}
};
  1. 将 Canvas 对象绘制到 Canvas 上下文中,并通过 wx.canvasToTempFilePath 方法将其保存为图片。

以上便是基于 Wxml2Canvas 在小程序中实现将 HTML 元素转换为 Canvas 对象并保存为图片的简单示例。