当前位置: 首页 > news >正文

Uniapp编写微信小程序,使用canvas进行绘图

一、canvas文档:

https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial

二、数据绘制(单位是像素):

1、绘制文本:

文字的长度超过设置的最大宽度,文字会缩在一起

① 填充文本(实心):

ctx.fillText("这里是文字", 开始绘制文本的点的 x 轴坐标, 开始绘制文本的点的 y 轴坐标[, 文字的最大宽度]);

② 边框文本(空心):

ctx.strokeText("这里是文字", 开始绘制文本的点的 x 轴坐标, 开始绘制文本的点的 y 轴坐标[, 文字的最大宽度]);

③ 文本超过最大宽度想要换行:

/**
* ctx:canvas元素
* x:开始绘制文本的点的 x 轴坐标
* y:开始绘制文本的点的 y 轴坐标
* lineHeight: 文本的行高
* maxWidth:文字的最大宽度
* 返回值:下一行文字的起始位置y坐标
**/ 
function drawWrappedText(ctx, text, x, y, lineHeight, maxWidth) {// Split text into words using spaces, filtering out empty stringsconst words = text.split(/\s+/g).filter(word => word.length > 0);let line = '';const lines = [];for (const word of words) {// Check if adding the word (with space) exceeds maxWidthconst testLine = line ? line + ' ' + word : word;const metrics = ctx.measureText(testLine);if (metrics.width > maxWidth) {if (line === '') {// Word is too long; split itlet splitIndex = 1;while (splitIndex < word.length) {const part = word.substring(0, splitIndex);if (ctx.measureText(part).width > maxWidth) break;splitIndex++;}splitIndex = Math.max(1, splitIndex - 1); // Adjust to fitlines.push(word.substring(0, splitIndex));line = word.substring(splitIndex); // Remaining part} else {// Push current line and start new line with the wordlines.push(line);line = word;}} else {line = testLine; // Add word to current line}}if (line) lines.push(line); // Add the last line// Draw each line and calculate nextStartlines.forEach((line, index) => {ctx.fillText(line, x, y + index * lineHeight, maxWidth);});return y + lines.length * lineHeight; // Next starting Y position
}

④ 文本样式:

ctx.font="文字大小 粗细 颜色 字体名称..."

2、绘制矩形:

① 填充矩形(实心):

ctx.fillStyle = '颜色'  // 这个是填充的颜色
ctx.fillRect(矩形左上角的起始点x, 矩形左上角的起始点y, 矩形的宽, 矩形的高); // 这个是填充矩形

② 边框矩形(空心):

ctx.strokeRect(边框左上角的起始点x, 边框左上角的起始点y, 边框的宽, 边框的高);
ctx.strokeStyle = '颜色' // 这个是矩形线条边框的颜色

3、绘制路径:

① 新建一条路径:ctx.beginPath()

② 移动笔触设置起点:ctx.moveTo(路径的起点x,路径的起点y);

③ 绘制路径:

(1)直线:

ctx.lineTo(直线结束点x,直线结束点y);

  • 只要线条轮廓:ctx.stroke()
  • 需要填充:ctx.fill()
(2)闭合路径绘制(连接起点和终点):

ctx.closePath()

(3)指定线条的宽度:
ctx.lineWidth = 数字

4、绘制图片:

图片尽量使用临时路径,即使用uni.canvasToTempFilePath()函数生成

① 微信小程序不允许使用new Image()

使用 canvas.createImage()

② 绘制图片是一个异步过程,要使用async\await进行处理

三、简单的使用代码:

1、 模版代码:

<canvas id="myCanvas" type="2d" :style="{ position: 'fixed', top: '-9999px', left: '-9999px', width: canvasWidth + 'px', height: canvasHeight + 'px' }"
></canvas>

2、js代码:

// 初始化canvas
async createCanvas(width, height) {return new Promise((resolve) => {const query = uni.createSelectorQuery().in(this);query.select('#myCanvas').fields({ node: true, size: true }).exec(res => {const canvas = res[0].node;// const dpr = uni.getSystemInfoSync().pixelRatio;// canvas.width = width * dpr;// canvas.height = height * dpr;canvas.width = widthcanvas.height = heightresolve(canvas);});});
},
// 点击某个按钮进行模版的绘制
async saveImg() {const that = this// 首先初始化canvasconst canvas = await that.createCanvas(图片的宽, 图片的高);const ctx = canvas.getContext('2d');// 拿到当前设备的像素比const dpr = uni.getSystemInfoSync().pixelRatio;// 绘制内容:await that.drawImage(canvas, ctx, 图片的临时路径, 221,58, 108, 108);
},
async drawImage(canvas,ctx, imagePath, x, y, width, height) {return new Promise((resolve) => {const img = canvas.createImage();img.src = imagePath;img.onload = () => {ctx.drawImage(img, x, y, width, height);resolve();};});
}

相关文章:

  • 企业如何将钉钉付款单高效集成到金蝶云星空?
  • 数智读书笔记系列032《统一星型模型--一种敏捷灵活的数据仓库和分析设计方法》
  • 开源数字人框架 AWESOME - DIGITAL - HUMAN:技术革新与行业标杆价值剖析
  • 从“山谷论坛”看AI七剑下天山
  • 十三、基于大模型的在线搜索平台——整合function calling流程
  • 【大语言模型ChatGPT4/4o 】“AI大模型+”多技术融合:赋能自然科学暨ChatGPT在地学、GIS、气象、农业、生态与环境领域中的应用
  • 捌拾叁- 量子傅里叶变换
  • 【深度学习】【目标检测】【Ultralytics-YOLO系列】YOLOV3核心文件detect.py解读
  • CSS:盒子模型
  • C# NX二次开发:宏录制实战讲解(第一讲)
  • 当当网Top500书籍信息爬取与分析
  • CSS transition过渡属性
  • # 交换排序:从冒泡到快速排序的深度解析
  • 全新UI彩虹外链网盘系统源码v5.6/前后端美化模板/整站+模版文件
  • 何时需要import css文件?怎么知道需要导入哪些css文件?为什么webpack不提示CSS导入?(导入css导入规则、css导入规范)
  • 【图像大模型】Stable Diffusion Web UI:深度解析与实战指南
  • istio in action之流量控制与路由
  • 高尔夫基本知识及规则·棒球1号位
  • Linux59 SSH配置前瞻 JumpServer双网卡ping通
  • 基于SSM实现的健身房系统功能实现八
  • 领证不用户口本,还需哪些材料?补领证件如何操作?七问七答
  • “毛茸茸”的画,诗意、温暖又治愈
  • 近4小时会谈、3项联合声明、20多份双边合作文本,中俄元首今年首次面对面会晤成果颇丰
  • 复旦发文缅怀文科杰出教授裘锡圭:曾提出治学需具备三种精神
  • 中俄元首今年首次面对面会谈,达成哪些新的重要共识?
  • 迪拜金融市场CEO:2024年市场表现出色,超八成新投资者来自海外