微信小程序-CANVAS写入图片素材、文字等数据生成图片

微信小程序中,CANVAS写入图片素材、文字等数据生成图片,最终可将生成的 base64 格式图片保存至相册操作

Tips:

1、canvas 标签默认宽度 300px、高度 150px
canvas 生成图片时,写入图片素材、文字等数据前,需要根据实际需求,设置 canvas 宽、高,
如以下示例中 设置 posterCanvas.width 及 posterCanvas.height

2、同一页面中的 canvas-id 不可重复,如果使用一个已经出现过的 canvas-id,该 canvas 标签对应的画布将被隐藏并不再正常工作
canvas 不可设置隐藏,否则不能正常工作,若不希望其显示的话,可以 如以下示例中 设置 CSS样式,
makeResCanvasW 、 makeResCanvasH 都设置为 0 ,
- 原生开发:
style="width: {{makeResCanvasW}}rpx;height: {{makeResCanvasH}}rpx;"

- uniapp开发:
:style="'width: ' + makeResCanvasW + 'rpx;height: ' + makeResCanvasH + 'rpx;'"

3、多次生成操作时,清除之前写入数据即可,不需要设置多个 canvas
如以下示例中 setCanvasCtx 方法设置
判断是否已有 Canvas 对象,无则设置 Canvas 对象 及 Canvas 绘制上下文 ctx,有则清除之前写入的数据

4、写入图片素材、文字等数据,与普通H5操作一致
写入图片设置:
注:使用网络图片时,使用 downloadFile 方法,下载文件资源到本地进行处理(返回文件的本地临时路径 (本地路径),单次下载允许的最大文件为 200MB)
如以下示例中 步骤:
- posterCanvas.createImage() 创建一个图片对象
- .src 设置图片的 URL
- .onload 图片加载完成后触发的回调函数,这里可以获取到此图片对象的宽高等数据
- .drawImage 画入图片数据
- 其他写入数据:与H5中处理基本一致

5、生成图片(base64 格式图片)
如以下示例中 posterCanvas.toDataURL('image/png') ,生成图片后,可使用 小程序预览图片方法 previewImage 方法查看生成的图片

6、base64 格式图片保存至相册
如以下示例中 base64ImageHandle 方法设置,
步骤:
- .env.USER_DATA_PATH : 指定图片的临时路径【.env 环境变量 .USER_DATA_PATH 文件系统中的用户目录路径 (本地路径)】
- getFileSystemManager : 获取小程序的文件系统(小程序获取全局唯一的文件管理器方法)
- .writeFile : 把arraybuffer数据写入到临时目录中(写文件)
- 使用小程序保存图片到系统相册方法 saveImageToPhotosAlbum,把临时路径下的图片,保存图片到相册

微信小程序-原生开发,处理代码如下:

wxml:

<canvas type="2d" id="makeResCanvas" style="width: {{makeResCanvasW}}rpx;height: {{makeResCanvasH}}rpx;"></canvas>

data中参数:

data: {makeResCanvasW : 0,makeResCanvasH : 0,
},

调用方法生成图片

this.makeResImg();

处理方法:

/*** CANVAS画布生成图片*/
makeResImg() {wx.showLoading({title: "生成中",mask: true});this.setCanvasCtx(()=>{this.makeResImgAfter();})
},
// 
setCanvasCtx(callback){if(this.data.posterCanvas){console.log(222)this.data.posterCtx.clearRect(0, 0, this.data.posterCanvas.width, this.data.posterCanvas.height);callback && callback();}else{console.log(111)const query = wx.createSelectorQuery();query.select('#makeResCanvas').fields({node: true,size: true}).exec((res) => {// console.log(res);this.setData({posterCanvas : res[0].node})this.setData({posterCtx : this.data.posterCanvas.getContext('2d')})this.data.posterCtx.clearRect(0, 0, this.data.posterCanvas.width, this.data.posterCanvas.height);callback && callback();})}
},
// 
makeResImgAfter(){// 写入 生成图片 背景图片const posterBgImg = this.data.posterCanvas.createImage();posterBgImg.src = '../../images/poster_bg.png';// this.getDownloadFile('https://xxxxxxxxx/poster_bg.png',(formimgTempFilePath)=>{// posterBgImg.src = formimgTempFilePath;posterBgImg.onload = () => {console.log('背景图实际宽高', posterBgImg.width, posterBgImg.height);this.data.posterCanvas.width = posterBgImg.width;this.data.posterCanvas.height = posterBgImg.height;this.setData({makeResCanvasW:0,makeResCanvasH:0,})// 画入背景图片this.data.posterCtx.drawImage(posterBgImg, 0, 0, posterBgImg.width, posterBgImg.height);// 写入 生成图片 勾选标识图片const checkImg = this.data.posterCanvas.createImage();checkImg.src = '../../images/check.png';// this.getDownloadFile('https://xxxxxxxxx/check.png',(checkTempFilePath)=>{// checkImg.src = checkTempFilePath;checkImg.onload = () => {// 画入勾选标识图片this.data.posterCtx.drawImage(checkImg, 20, 188, 32, 24);this.data.posterCtx.drawImage(checkImg, 20 + 42, 188, 32, 24);this.data.posterCtx.drawImage(checkImg, 20 + 42 + 42, 188, 32, 24);this.data.posterCtx.drawImage(checkImg, 20 + 42 + 42 + 42, 188, 32, 24);this.data.posterCtx.drawImage(checkImg, 20 + 42 + 42 + 42 + 42, 188, 32, 24);this.data.posterCtx.drawImage(checkImg, 20 + 42 + 42 + 42 + 42 + 42, 188, 32, 24);// 写入文本this.data.posterCtx.fillStyle = '#000000';this.data.posterCtx.textAlign = 'left';this.data.posterCtx.textBaseline = 'top';this.data.posterCtx.font = '26px "PingFangSC-Regular","STHeitiSC-Light","微软雅黑","Microsoft YaHei","sans-serif"';// 写入单行文本this.data.posterCtx.fillText('写入单行文本',10,60);// 写入多行文本this.writeTextOnCanvas(this.data.posterCtx, 36, 40, '写入多行文本写入多行文本写入多行文本写入多行文本写入多行文本写入多行文本' ,10, 100);// 生成图片this.setData({posterUrl: this.data.posterCanvas.toDataURL('image/png'),})// 查看生成的图片setTimeout(()=>{wx.previewImage({current: this.data.posterUrl,urls: [this.data.posterUrl]});},10)wx.hideLoading();// base64图片保存至相册setTimeout(()=>{this.base64ImageHandle(this.data.posterUrl);},10)}// })}// })
},
// 写入多行文本
writeTextOnCanvas(ctx_2d, lineheight, bytelength, text ,startleft, starttop){function getTrueLength(str){var len = str.length, truelen = 0;for(var x = 0; x < len; x++){if(str.charCodeAt(x) > 128){truelen += 2;}else{truelen += 1;}}return truelen;}function cutString(str, leng){var len = str.length, tlen = len, nlen = 0;for(var x = 0; x < len; x++){if(str.charCodeAt(x) > 128){if(nlen + 2 < leng){nlen += 2;}else{tlen = x;break;}}else{if(nlen + 1 < leng){nlen += 1;}else{tlen = x;break;}}}return tlen;}for(var i = 1; getTrueLength(text) > 0; i++){var tl = cutString(text, bytelength);ctx_2d.fillText(text.substr(0, tl).replace(/^\s+|\s+$/, ""), startleft, (i-1) * lineheight + starttop);text = text.substr(tl);}
},
// 下载网络图片
getDownloadFile(img,callback){wx.downloadFile({url: img,success (res) {if (res.statusCode === 200) {callback && callback(res.tempFilePath)}}})
},
// base64图片保存至相册
base64ImageHandle(base64) {// 指定图片的临时路径const path = `${wx.env.USER_DATA_PATH}/reportformImg.png`// 获取小程序的文件系统const fsm = wx.getFileSystemManager()// 把arraybuffer数据写入到临时目录中fsm.writeFile({filePath: path,data: base64.replace(/^data:image\/\w+;base64,/, ''),encoding: 'base64',success: () => {wx.hideLoading();wx.showModal({title: '保存图片',content: '保存数据报表图片至手机相册?',success: (result) => {if (result.confirm) {// 把临时路径下的图片,保存至相册wx.saveImageToPhotosAlbum({filePath: path,success: () => {wx.showToast({title: '保存海报成功',icon: 'success',duration: 2000})}})}}})}})
},

微信小程序-uniapp开发,处理代码如下:

.vue:

<canvas type="2d" id="makeResCanvas" :style="'width: ' + makeResCanvasW + 'rpx;height: ' + makeResCanvasH + 'rpx;'"></canvas>

data中参数:

data() {return {makeResCanvasW:0,makeResCanvasH:0,};
},

调用方法生成图片

this.makeResImg();

处理方法:

/*** CANVAS画布生成图片*/
makeResImg() {uni.showLoading({title: "生成中",mask: true});this.setCanvasCtx(()=>{this.makeResImgAfter();})
},
// 
setCanvasCtx(callback){if(this.posterCanvas){console.log(222)this.posterCtx.clearRect(0, 0, this.posterCanvas.width, this.posterCanvas.height);callback && callback();}else{console.log(111)const query = uni.createSelectorQuery();query.select('#makeResCanvas').fields({node: true,size: true}).exec((res) => {// console.log(res);this.posterCanvas = res[0].node;this.posterCtx = this.posterCanvas.getContext('2d');this.posterCtx.clearRect(0, 0, this.posterCanvas.width, this.posterCanvas.height);callback && callback();})}
},
// 
makeResImgAfter(){// 写入 生成图片 背景图片const posterBgImg = this.posterCanvas.createImage();posterBgImg.src = '/static/images/xjshop/poster_bg.png';// this.getDownloadFile('https://xxxxxxxxx/poster_bg.png',(formimgTempFilePath)=>{// posterBgImg.src = formimgTempFilePath;posterBgImg.onload = () => {// console.log('背景图实际宽高', posterBgImg.width, posterBgImg.height);this.posterCanvas.width = posterBgImg.width;this.posterCanvas.height = posterBgImg.height;this.makeResCanvasW = 0;this.makeResCanvasH = 0;// 画入背景图片this.posterCtx.drawImage(posterBgImg, 0, 0, posterBgImg.width, posterBgImg.height);// 写入 生成图片 勾选标识图片const checkImg = this.posterCanvas.createImage();// checkImg.src = '/static/images/xjshop/check.png';this.getDownloadFile('https://xxxxxxxxx/check.png',(checkTempFilePath)=>{checkImg.src = checkTempFilePath;checkImg.onload = () => {// 画入勾选标识图片this.posterCtx.drawImage(checkImg, 20, 188, 32, 24);this.posterCtx.drawImage(checkImg, 20 + 42, 188, 32, 24);this.posterCtx.drawImage(checkImg, 20 + 42 + 42, 188, 32, 24);this.posterCtx.drawImage(checkImg, 20 + 42 + 42 + 42, 188, 32, 24);this.posterCtx.drawImage(checkImg, 20 + 42 + 42 + 42 + 42, 188, 32, 24);this.posterCtx.drawImage(checkImg, 20 + 42 + 42 + 42 + 42 + 42, 188, 32, 24);// 写入文本this.posterCtx.fillStyle = '#000000';this.posterCtx.textAlign = 'left';this.posterCtx.textBaseline = 'top';this.posterCtx.font = '26px "PingFangSC-Regular","STHeitiSC-Light","微软雅黑","Microsoft YaHei","sans-serif"';// 写入单行文本this.posterCtx.fillText('写入单行文本',10,60);// 写入多行文本this.writeTextOnCanvas(this.posterCtx, 36, 40, '写入多行文本写入多行文本写入多行文本写入多行文本写入多行文本写入多行文本' ,10, 100);// 生成图片this.posterUrl = this.posterCanvas.toDataURL('image/png')// 查看生成的图片setTimeout(()=>{uni.previewImage({current: this.posterUrl,urls: [this.posterUrl]});},10)uni.hideLoading();// base64图片保存至相册setTimeout(()=>{this.base64ImageHandle(this.posterUrl);},10)}})}// })
},
// 写入多行文本
writeTextOnCanvas(ctx_2d, lineheight, bytelength, text ,startleft, starttop){function getTrueLength(str){var len = str.length, truelen = 0;for(var x = 0; x < len; x++){if(str.charCodeAt(x) > 128){truelen += 2;}else{truelen += 1;}}return truelen;}function cutString(str, leng){var len = str.length, tlen = len, nlen = 0;for(var x = 0; x < len; x++){if(str.charCodeAt(x) > 128){if(nlen + 2 < leng){nlen += 2;}else{tlen = x;break;}}else{if(nlen + 1 < leng){nlen += 1;}else{tlen = x;break;}}}return tlen;}for(var i = 1; getTrueLength(text) > 0; i++){var tl = cutString(text, bytelength);ctx_2d.fillText(text.substr(0, tl).replace(/^\s+|\s+$/, ""), startleft, (i-1) * lineheight + starttop);text = text.substr(tl);}
},
// 下载网络图片
getDownloadFile(img,callback){uni.downloadFile({url: img,success (res) {if (res.statusCode === 200) {callback && callback(res.tempFilePath)}}})
},
// base64图片保存至相册
base64ImageHandle(base64) {// 指定图片的临时路径const path = `${uni.env.USER_DATA_PATH}/reportformImg.png`// 获取小程序的文件系统const fsm = uni.getFileSystemManager()// 把arraybuffer数据写入到临时目录中fsm.writeFile({filePath: path,data: base64.replace(/^data:image\/\w+;base64,/, ''),encoding: 'base64',success: () => {uni.hideLoading();uni.showModal({title: '保存图片',content: '保存数据报表图片至手机相册?',success: (result) => {if (result.confirm) {// 把临时路径下的图片,保存至相册uni.saveImageToPhotosAlbum({filePath: path,success: () => {uni.showToast({title: '保存海报成功',icon: 'success',duration: 2000})}})}}})}})
},

素材图片

原生开发 生成图片

uniapp开发 生成图片

 下载图片提示

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1486143.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

LangChain的使用详解

一、 概念介绍 1.1 Langchain 是什么&#xff1f; 官方定义是&#xff1a;LangChain是一个强大的框架&#xff0c;旨在帮助开发人员使用语言模型构建端到端的应用程序&#xff0c;它提供了一套工具、组件和接口&#xff0c;可简化创建由大型语言模型 (LLM) 和聊天模型提供…

nfs和web服务器的搭建

&#xff08;一&#xff09;web服务器的搭建 1.配置基本环境 要点有&#xff0c;yum源&#xff0c;包含nginx和阿里云&#xff08;或者腾讯云或者华为云&#xff09;&#xff0c;这里的相关知识可以参考之前的yum配置笔记 2.安装nginx yum -y install nginx 3.验证并且开启服…

VS Code 配置 C/C++ 编程运行环境(保姆级教程)

文章目录 一、软件下载1. 下载 VS Code 安装工具 2. 下载 MinGW-W64二、安装 VS Code三、安装 MinGW-W64 及配置环境变量四、配置 VS Code 的 C/C 编程运行环境1. 汉化 VS Code&#xff08;选做&#xff09;2. 安装 C/C 扩展包 五、测试 VS Code 的 C/C 编程环境1. 创建代码文件…

C++学习笔记01-语法基础(问题-解答自查版)

前言 以下问题以Q&A形式记录&#xff0c;基本上都是笔者在初学一轮后&#xff0c;掌握不牢或者频繁忘记的点 Q&A的形式有助于学习过程中时刻关注自己的输入与输出关系&#xff0c;也适合做查漏补缺和复盘。 本文对读者可以用作自查&#xff0c;答案在后面&#xff0…

求职学习day8

7/21回顾&#xff1a; 用面试鸭的意义可能就在于将知识点用问答的形式具象化在脑海&#xff0c;不然可能只停留在听说过的感觉 7.21 玩了一天。一个很不好的信号。今天下午要试试把 mall 项目的代码运行过一遍。 项目运行问题&#xff1a; 问题 1 &#xff1a;两个门服务器…

【HarmonyOS】HarmonyOS NEXT学习日记:六、渲染控制、样式结构重用

【HarmonyOS】HarmonyOS NEXT学习日记&#xff1a;六、渲染控制、样式&结构重用 渲染控制包含了条件渲染和循环渲染&#xff0c;所谓条件渲染&#xff0c;即更具状态不同&#xff0c;选择性的渲染不同的组件。 而循环渲染则是用于列表之内的、多个重复元素组成的结构中。 …

Redis集群部署Windows版本

Redis集群 之前因为数据量的原因&#xff0c;并没有进行Redis集群的配置需要&#xff0c;现在由于数据量大&#xff0c;需要进行集群部署。 最初在windows系统部署&#xff0c;需要Redis的windows版本&#xff0c;但官方没有windows版本&#xff0c;所以需要去gitHub上找由民…

R语言统计分给——数据管理2

参考资料&#xff1a;R语言实战【第2版】 1、日期值 日期值通常以字符串的形式输入R中&#xff0c;然后转化为数值形式存储的日期边阿玲。函数as.Date()用于执行这种转化。其语法为as.Date(x,"input_format")&#xff0c;其中x是字符型数据&#xff0c;input_format…

Ubuntu 24.04 LTS Noble安装 FileZilla Server

FileZilla Server 是一款使用图形用户界面快速创建 FTP 服务器的软件。它有助于测试需要 FTP 服务器功能的各种项目。虽然早期的 FileZilla FTP 服务器仅适用于 Windows 和 macOS&#xff0c;但现在我们也可以在 Linux&#xff08;例如 Ubuntu 24.04&#xff09;上安装 FileZil…

CatBoost模型Python代码——用CatBoost模型实现机器学习

一、CatBoost模型简介 1.1适用范围 CatBoost&#xff08;Categorical Boosting&#xff09;是一种基于梯度提升的机器学习算法&#xff0c;特别适用于处理具有类别特征的数据集。它可以用于分类、回归和排序任务&#xff0c;并且在处理具有大量类别特征的数据时表现优异。典型…

安装好anaconda,打开jupyter notebook,新建 报500错

解决办法&#xff1a; 打开anaconda prompt 输入 jupyter --version 重新进入jupyter notebook&#xff1a; 可以成功进入进行代码编辑

你了解你的GD32 MCU系统主频是多少吗 ?

系统时钟是GD32 MCU的时基&#xff0c;可以理解为系统的心跳&#xff0c;片上所有的外设以及CPU最原始的时钟都来自于系统时钟&#xff0c;因而明确当前系统时钟是多少非常重要&#xff0c;只有明确了系统时钟&#xff0c;才能够实现准确的定时、准确的采样间隔以及准确的通信速…

回溯题目的套路总结

前言 昨天写完了LeeCode的7&#xff0c;8道回溯算法的题目&#xff0c;写一下总结&#xff0c;这类题目的共同特点就是暴力搜索问题&#xff0c;排列组合或者递归&#xff0c;枚举出所有可能的答案&#xff0c;思路很简单&#xff0c;实现起来的套路也很通用&#xff0c;一…

win10安装ElasticSearch7.x和分词插件

说明&#xff1a; 以下内容整理自网络&#xff0c;格式调整优化&#xff0c;更易阅读&#xff0c;希望能对需要的人有所帮助。 一 安装 Java环境 ElasticSearch使用Java开发的&#xff0c;依赖Java环境&#xff0c;安装 ElasticSearch 7.x 之前&#xff0c;需要先安装jdk-8。…

unity 实现图片的放大与缩小(根据鼠标位置拉伸放缩)

1创建UnityHelper.cs using UnityEngine.Events; using UnityEngine.EventSystems;public class UnityHelper {/// <summary>/// 简化向EventTrigger组件添加事件的操作。/// </summary>/// <param name"_eventTrigger">要添加事件监听的UI元素上…

系统架构设计师①:计算机组成与体系结构

系统架构设计师①&#xff1a;计算机组成与体系结构 计算机结构 计算机的组成结构可以概括为以下几个主要部分&#xff1a;中央处理器&#xff08;CPU&#xff09;、存储器&#xff08;包括主存和外存&#xff09;、输入设备、输出设备&#xff0c;以及控制器、运算器、总线和…

下拉菜单过渡

下拉过渡&#xff0c;利用Y轴的transform&#xff1a;scaleY(0) —》transform&#xff1a;scaleY(1) 代码&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8" /><meta name"viewport" cont…

C2W3.Assignment.Language Models: Auto-Complete.Part1

理论课&#xff1a;C2W3.Auto-complete and Language Models 文章目录 1 Load and Preprocess Data1.1: Load the data1.2 Pre-process the dataExercise 01.Split data into sentencesExercise 02.Tokenize sentencesExercise 03Split into train and test sets Exercise 04H…

2024.7.22 作业

1.将双向链表和循环链表自己实现一遍&#xff0c;至少要实现创建、增、删、改、查、销毁工作 循环链表 looplinklist.h #ifndef LOOPLINKLIST_H #define LOOPLINKLIST_H#include <myhead.h>typedef int datatype;typedef struct Node {union {int len;datatype data;}…

K8S 部署peometheus + grafana 监控

安装说明 如果有下载不下来的docker镜像可以私信我免费下载。 系统版本为 Centos7.9 内核版本为 6.3.5-1.el7 K8S版本为 v1.26.14 动态存储&#xff1a;部署文档 GitHub地址 下载yaml 文件 ## 因为我的K8S 版本比较新&#xff0c;我下载的是当前的最新版本&#xff0c;你的要…