微信小程序--canvas画布实现图片的编辑

这篇具有很好参考价值的文章主要介绍了微信小程序--canvas画布实现图片的编辑。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

概述

上传图片,编辑图片大小,添加文字,改变文字颜色等

详细

概述

微信小程序--canvas画布实现图片的编辑

详细

一、前期准备工作

软件环境:微信开发者工具
官方下载地址:微信开发者工具下载地址与更新日志 | 微信开放文档

1、基本需求。
  • 实现上传图片

  • 实现图片编辑

  • 实现添加文字

  • 实现导出图片

2、案例目录结构

微信小程序canvas,微信及其他应用,微信小程序,小程序

二、程序实现具体步骤
1.index.js代码(canvas-drag)
// components/canvas-drag/index.js
const dragGraph = function ({ x, y, w, h, type, text, fontSize = 20, color = 'red', url }, canvas, factor) {
if (type === 'text') {
canvas.setFontSize(fontSize);
const textWidth = canvas.measureText(this.text).width;
const textHeight = fontSize + 10;
const halfWidth = textWidth / 2;
const halfHeight = textHeight / 2;
this.x = x + halfWidth;
this.y = y + halfHeight;
} else {
this.x = x;
this.y = y;
}
this.w = w;
this.h = h;
this.fileUrl = url;
this.text = text;
this.fontSize = fontSize;
this.color = color;
this.ctx = canvas;
this.rotate = 0;
this.type = type;
this.selected = true;
this.factor = factor;
this.MIN_WIDTH = 50;
this.MIN_FONTSIZE = 10;
}

dragGraph.prototype = {
/**
     * 绘制元素
     */
paint() {
this.ctx.save();
// TODO 剪切
// this._drawRadiusRect(0, 0, 700, 750, 300);
// this.ctx.clip();
// 由于measureText获取文字宽度依赖于样式,所以如果是文字元素需要先设置样式
if (this.type === 'text') {
this.ctx.setFontSize(this.fontSize);
this.ctx.setTextBaseline('middle');
this.ctx.setTextAlign('center');
this.ctx.setFillStyle(this.color);
}
// 选择区域的中心点
this.centerX = this.type === 'text' ? this.x : this.x + (this.w / 2);
this.centerY = this.type === 'text' ? this.y : this.y + (this.h / 2);
// 旋转元素
this.ctx.translate(this.centerX, this.centerY);
this.ctx.rotate(this.rotate * Math.PI / 180);
this.ctx.translate(-this.centerX, -this.centerY);
// 渲染元素
if (this.type === 'text') {
this.ctx.fillText(this.text, this.x, this.y);
} else if (this.type === 'image') {
this.ctx.drawImage(this.fileUrl, this.x, this.y, this.w, this.h);
}
// 如果是选中状态,绘制选择虚线框,和缩放图标、删除图标
if (this.selected) {
this.ctx.setLineDash([10, 10]);
this.ctx.setLineWidth(2);
this.ctx.setStrokeStyle('red');
this.ctx.lineDashOffset = 10;

if (this.type === 'text') {
const textWidth = this.ctx.measureText(this.text).width;
const textHeight = this.fontSize + 10
const halfWidth = textWidth / 2;
const halfHeight = textHeight / 2;
const textX = this.x - halfWidth;
const textY = this.y - halfHeight;
this.ctx.strokeRect(textX, textY, textWidth, textHeight);
this.ctx.drawImage('./icon/close.png', textX - 15, textY - 15, 30, 30);
this.ctx.drawImage('./icon/scale.png', textX + textWidth - 15, textY + textHeight - 15, 30, 30);
} else {
this.ctx.strokeRect(this.x, this.y, this.w, this.h);
this.ctx.drawImage('./icon/close.png', this.x - 15, this.y - 15, 30, 30);
this.ctx.drawImage('./icon/scale.png', this.x + this.w - 15, this.y + this.h - 15, 30, 30);
}
}

this.ctx.restore();
},
/**
     * 判断点击的坐标落在哪个区域
     * @param {*} x 点击的坐标
     * @param {*} y 点击的坐标
     */
isInGraph(x, y) {
const selectW = this.type === 'text' ? this.ctx.measureText(this.text).width : this.w;
const selectH = this.type === 'text' ? this.fontSize + 10 : this.h;

// 删除区域左上角的坐标和区域的高度宽度
const delW = 30;
const delH = 30;
const delX = this.type === 'text' ? this.x - (selectW / 2) : this.x;
const delY = this.type === 'text' ? this.y - (selectH / 2) : this.y;
// 旋转后的删除区域坐标
const transformDelX = this._getTransform(delX, delY, this.rotate - this._getAngle(this.centerX, this.centerY, delX, delY)).x - (delW / 2);
const transformDelY = this._getTransform(delX, delY, this.rotate - this._getAngle(this.centerX, this.centerY, delX, delY)).y - (delH / 2);

// 变换区域左上角的坐标和区域的高度宽度
const scaleW = 30;
const scaleH = 30;
const scaleX = this.type === 'text' ? this.x + (selectW / 2) : this.x + selectW;
const scaleY = this.type === 'text' ? this.y + (selectH / 2) : this.y + selectH;
// 旋转后的变换区域坐标
const transformScaleX = this._getTransform(scaleX, scaleY, this.rotate + this._getAngle(this.centerX, this.centerY, scaleX, scaleY)).x - (scaleW / 2);
const transformScaleY = this._getTransform(scaleX, scaleY, this.rotate + this._getAngle(this.centerX, this.centerY, scaleX, scaleY)).y - (scaleH / 2);

const moveX = this.type === 'text' ? this.x - (selectW / 2) : this.x;
const moveY = this.type === 'text' ? this.y - (selectH / 2) : this.y;

// 测试使用
// this.ctx.setLineWidth(1);
// this.ctx.setStrokeStyle('red');
// this.ctx.strokeRect(transformDelX, transformDelY, delW, delH);

// this.ctx.setLineWidth(1);
// this.ctx.setStrokeStyle('black');
// this.ctx.strokeRect(transformScaleX, transformScaleY, scaleW, scaleH);

if (x - transformScaleX >= 0 && y - transformScaleY >= 0 &&
transformScaleX + scaleW - x >= 0 && transformScaleY + scaleH - y >= 0) {
// 缩放区域
return 'transform';
} else if (x - transformDelX >= 0 && y - transformDelY >= 0 &&
transformDelX + delW - x >= 0 && transformDelY + delH - y >= 0) {
// 删除区域
return 'del';
} else if (x - moveX >= 0 && y - moveY >= 0 &&
moveX + selectW - x >= 0 && moveY + selectH - y >= 0) {
// 移动区域
return 'move';
}
// 不在选择区域里面
return false;
},
/**
     * 两点求角度
     * @param {*} px1 
     * @param {*} py1 
     * @param {*} px2 
     * @param {*} py2 
     */
_getAngle(px1, py1, px2, py2) {
const x = px2 - px1;
const y = py2 - py1;
const hypotenuse = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
//斜边长度
const cos = x / hypotenuse;
const radian = Math.acos(cos);
const angle = 180 / (Math.PI / radian);
return angle;
},
/**
     * 点选择一定角度之后的坐标
     * @param {*} x 
     * @param {*} y 
     * @param {*} rotate 旋转的角度
     */
_getTransform(x, y, rotate) {
const angle = (Math.PI / 180) * (rotate);
const r = Math.sqrt(Math.pow((x - this.centerX), 2) + Math.pow((y - this.centerY), 2));
const a = Math.sin(angle) * r;
const b = Math.cos(angle) * r;
return {
x: this.centerX + b,
y: this.centerY + a,
};
},
/**
     * 
     * @param {*} px 手指按下去的坐标
     * @param {*} py 手指按下去的坐标
     * @param {*} x 手指移动到的坐标
     * @param {*} y 手指移动到的坐标
     * @param {*} currentGraph 当前图层的信息
     */
transform(px, py, x, y, currentGraph) {
// 获取选择区域的宽度高度
if (this.type === 'text') {
this.ctx.setFontSize(this.fontSize);
}

const centerX = this.type === 'text' ? this.x : this.x + (this.w / 2);
const centerY = this.type === 'text' ? this.y : this.y + (this.h / 2);

const diffXBefore = px - centerX;
const diffYBefore = py - centerY;
const diffXAfter = x - centerX;
const diffYAfter = y - centerY;

const angleBefore = Math.atan2(diffYBefore, diffXBefore) / Math.PI * 180;
const angleAfter = Math.atan2(diffYAfter, diffXAfter) / Math.PI * 180;

// 旋转的角度
this.rotate = currentGraph.rotate + angleAfter - angleBefore;

const lineA = Math.sqrt(Math.pow((centerX - px), 2) + Math.pow((centerY - py), 2));
const lineB = Math.sqrt(Math.pow((centerX - x), 2) + Math.pow((centerY - y), 2));
if (this.type === 'image') {
const w = currentGraph.w + (lineB - lineA);
const h = currentGraph.h + (lineB - lineA);
this.w = w <= this.MIN_WIDTH ? this.MIN_WIDTH : w;
this.h = h <= this.MIN_WIDTH ? this.MIN_WIDTH : h;

if (w > this.MIN_WIDTH && h > this.MIN_WIDTH) {
// 放大 或 缩小
this.x = currentGraph.x - (lineB - lineA) / 2;
this.y = currentGraph.y - (lineB - lineA) / 2;
}
} else if (this.type === 'text') {
const fontSize = currentGraph.fontSize * ((lineB - lineA) / lineA + 1);
this.fontSize = fontSize <= this.MIN_FONTSIZE ? this.MIN_FONTSIZE : fontSize;
}
},
/**
     * 画圆角矩形
     */
_drawRadiusRect(x, y, w, h, r) {
const br = r / 2;
this.ctx.beginPath();
this.ctx.moveTo(this.toPx(x + br), this.toPx(y));    // 移动到左上角的点
this.ctx.lineTo(this.toPx(x + w - br), this.toPx(y));
this.ctx.arcTo(this.toPx(x + w), this.toPx(y), this.toPx(x + w), this.toPx(y + br), this.toPx(br));
this.ctx.lineTo(this.toPx(x + w), this.toPx(y + h - br));
this.ctx.arcTo(this.toPx(x + w), this.toPx(y + h), this.toPx(x + w - br), this.toPx(y + h), this.toPx(br));
this.ctx.lineTo(this.toPx(x + br), this.toPx(y + h));
this.ctx.arcTo(this.toPx(x), this.toPx(y + h), this.toPx(x), this.toPx(y + h - br), this.toPx(br));
this.ctx.lineTo(this.toPx(x), this.toPx(y + br));
this.ctx.arcTo(this.toPx(x), this.toPx(y), this.toPx(x + br), this.toPx(y), this.toPx(br));
},
toPx(rpx) {
return rpx * this.factor;
},
}
Component({
/**
     * 组件的属性列表
     */
properties: {
graph: {
type: Object,
value: {},
observer: 'onGraphChange',
},
bgColor: {
type: String,
value: '',
},
bgImage: {
type: String,
value: '',
},
width: {
type: Number,
value: 750,
},
height: {
type: Number,
value: 750,
},
},

/**
     * 组件的初始数据
     */
data: {

},

attached() {
const sysInfo = wx.getSystemInfoSync();
const screenWidth = sysInfo.screenWidth;
this.factor = screenWidth / 750;

if (typeof this.drawArr === 'undefined') {
this.drawArr = [];
}
this.ctx = wx.createCanvasContext('canvas-label', this);
this.draw();
},

/**
     * 组件的方法列表
     */
methods: {
toPx(rpx) {
return rpx * this.factor;
},
onGraphChange(n, o) {
if (JSON.stringify(n) === '{}') return;
this.drawArr.push(new dragGraph(Object.assign({
x: 30,
y: 30,
}, n), this.ctx, this.factor));
this.draw();
},
draw() {
if (this.data.bgImage !== '') {
this.ctx.drawImage(this.data.bgImage, 0, 0, this.toPx(this.data.width), this.toPx(this.data.height));
}
if (this.data.bgColor !== '') {
this.ctx.save();
this.ctx.setFillStyle(this.data.bgColor);
this.ctx.fillRect(0, 0, this.toPx(this.data.width), this.toPx(this.data.height));
this.ctx.restore();
}
this.drawArr.forEach((item) => {
item.paint();
});
return new Promise((resolve) => {
this.ctx.draw(false, () => {
resolve();
});
});
},
start(e) {
const { x, y } = e.touches[0];
this.tempGraphArr = [];
this.drawArr && this.drawArr.forEach((item, index) => {
item.selected = false;
const action = item.isInGraph(x, y);
if (action) {
if (action === 'del') {
this.drawArr.splice(index, 1);
this.ctx.clearRect(0, 0, this.toPx(this.data.width), this.toPx(this.data.height));
this.ctx.draw();
} else if (action === 'transform' || action === 'move') {
item.action = action;
this.tempGraphArr.push(item);
// 保存点击时的坐标
this.currentTouch = { x, y };

}
}
});
// 保存点击时元素的信息
if (this.tempGraphArr.length > 0) {
const lastIndex = this.tempGraphArr.length - 1;
this.tempGraphArr[lastIndex].selected = true;
this.currentGraph = Object.assign({}, this.tempGraphArr[lastIndex]);
}
this.draw();
},
move(e) {
const { x, y } = e.touches[0];
if (this.tempGraphArr && this.tempGraphArr.length > 0) {
const currentGraph = this.tempGraphArr[this.tempGraphArr.length - 1];
if (currentGraph.action === 'move') {
currentGraph.x = this.currentGraph.x + (x - this.currentTouch.x);
currentGraph.y = this.currentGraph.y + (y - this.currentTouch.y);
} else if (currentGraph.action === 'transform') {
currentGraph.transform(this.currentTouch.x, this.currentTouch.y, x, y, this.currentGraph);
}
this.draw();
}
},
end(e) {
this.tempGraphArr = [];
},
export() {
return new Promise((resolve, reject) => {
this.drawArr = this.drawArr.map((item) => {
item.selected = false;
return item;
});
this.draw().then(() => {
wx.canvasToTempFilePath({
canvasId: 'canvas-label',
success: (res) => { resolve(res.tempFilePath); },
fail: (e) => { reject(e); },
}, this);
});
})
},
changColor(color) {
const selected = this.drawArr.filter((item) => item.selected);
if (selected.length > 0) {
selected[0].color = color;
}
this.draw();
},
changeBgColor(color) {
this.data.bgImage = '';
this.data.bgColor = color;
this.draw();
},
changeBgImage(url) {
this.data.bgColor = '';
this.data.bgImage = url;
this.draw();
}
}
})

2.index.wxss代码(canvas-drag)
/* components/canvas-drag/index.wxss */
.movable-label {
margin-top: 300rpx;
width: 750rpx;    
height: 400rpx;
background: #eee;
}
.movable-block {
width: 120rpx;
height: 120rpx;
background: #ccc;
}
.movable-block .image-con {
width: 100%;
height: 100%;
}
3.index.wxml代码(canvas-drag)
<!--components/canvas-drag/index.wxml-->
<canvas canvas-id='canvas-label' 
disable-scroll="true"
bindtouchstart="start"
bindtouchmove="move"
bindtouchend="end"
style='width: {{width}}rpx; height: {{height}}rpx;'></canvas>
4.index.js逻辑代码(index)

a.部分的功能实现

import CanvasDrag from '../../components/canvas-drag/canvas-drag';
Page({
data: {
graph: {},
},
/**
     * 添加测试图片
     */
onAddTest() {
this.setData({
graph: {
w: 120,
h: 120,
type: 'image',
url: '../../assets/images/test.jpg',
}
});
},
/**
     * 添加图片
     */
onAddImage() {
wx.chooseImage({
success: (res) => {
this.setData({
graph: {
w: 200,
h: 200,
type: 'image',
url: res.tempFilePaths[0],
}
});
}
})
},
/**
     * 添加文本
     */
onAddText() {
this.setData({
graph: {
type: 'text',
text: 'helloworld',
}
});
},
/**
     * 导出图片
     */
onExport() {
CanvasDrag.export()
.then((filePath) => {
console.log(filePath);
wx.previewImage({
urls: [filePath]
})
})
.catch((e) => {
console.error(e);
})
},
/**
     * 改变文字颜色
     */
onChangeColor() {
CanvasDrag.changFontColor('blue');
},
/**
     * 改变背景颜色
     */
onChangeBgColor() {
CanvasDrag.changeBgColor('yellow');
},
/**
     * 改变背景照片
     */
onChangeBgImage() {
CanvasDrag.changeBgImage('../../assets/images/test.jpg');
},

})
三、案例运行效果图

微信小程序canvas,微信及其他应用,微信小程序,小程序

四、总结与备注

暂无文章来源地址https://www.toymoban.com/news/detail-755191.html

到了这里,关于微信小程序--canvas画布实现图片的编辑的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序中使用画布canvas实现动态心电图绘制

    大家好,我是雄雄。 近期,接了个项目,三端(小程序、PC、公众号)同步开发,PC端没的问题,以前一直做的就是PC端,但是小程序和公众号之前没有做过,只能通过这个项目,边做边学了。 人家都说小程序用原生的特别难,大部分都用 uniapp 开发,说是这个方便快捷,还能

    2024年02月09日
    浏览(32)
  • uni-app 微信小程序中如何通过 canvas 画布实现电子签名?

    一、实际应用场景 电子签名软件应用场景:电子签名在金融、银行、贷款行业中可以用于对内日常办公流转的文档的盖章签字,对外涉及业务合作协议,采购合同,贷款申请、信用评估、贷款合同、贷款文件表、说明函等等。 可以说,只要是涉及纸质文档签字盖章的场景,

    2024年02月10日
    浏览(36)
  • 微信小程序canvas画布不清晰解决方法

    绘制的图片,文字等十分模糊 添加以下代码,通过设置分辨率来解决 完整代码: 模糊不清的时候 多多进行调试一下就可以了 多尝试新方案 

    2024年02月10日
    浏览(49)
  • 微信小程序canvas画布绘制文字自动换行

    关键步骤介绍: text为需要绘制的文本,通过换行符将text分割为words数组。 basic_height为第一行文本的高度。 get_canvas_row函数根据行宽限制将输入文本转化为不同的行,实现见下文。 text_size为设置的文本高度,h+text_size*j为每行待绘制文本的高度,绘制完成后更新h。 get_canvas_

    2024年01月17日
    浏览(41)
  • 微信小程序 canvas画布clip()在ios端多次裁剪无效

    最近在使用canvas绘制用户电子名片时,由于第一次使用不够熟悉,在绘制名片时根据顺序需要先裁剪出名片的形状及边角圆; 然后再在卡片区域中绘制头像,由于头像需要裁剪一个斜角线,于是需要使用到clip()进行二次裁剪,裁剪后在安卓手机显示一切正常,但在ios端测试时

    2024年02月13日
    浏览(30)
  • 使用taro+canvas实现微信小程序的图片分享功能

    二轮充电业务中,用户充电完成后在订单详情页展示订单相关信息,用户点击分享按钮唤起微信小程序分享菜单,将生成的图片海报分享给微信好友或者下载到本地,好友可通过扫描海报中的二维码加群领取优惠。 使用场景及功能:微信小程序 生成海报图片 分享好友 下载图

    2024年02月05日
    浏览(49)
  • 微信小程序使用canvas绘制网络图片,使用canvas将图片变成圆形

    以上的写法 会造成某些图标无法绘制上去, 解决方法是在网络图片中不断嵌套,先绘制大图片,再绘制小图片的顺序 网上说使用先下载到本地,再使用img.src加载,我尝试过还是不行 长用在海报,需要将用户的头像画到canvas图片上,如: 其原理就是在图片上面放一个圆

    2024年02月13日
    浏览(46)
  • 微信小程序canvas绘制自适应图片,UniApp canvas绘制自适应图片

     需求:画布宽高为686 * 686 的正方形(可以进行调整根据自身需要来)             当图片宽度大于高度时,对图片宽度进行裁剪              当图片高度大于宽度时,对图片高度进行裁剪              我是用uniApp进行开发的,如果是小程序原生,直接把“uni” 改为 “

    2024年02月09日
    浏览(42)
  • 【小程序图片水印】微信小程序图片加水印功能 canvas绘图

    感觉有用的话,可以打赏一把么?一毛不嫌少,十块不嫌多 更多详细代码请关注公众号索取(备注:公众号):

    2024年04月29日
    浏览(33)
  • 微信小程序 新版canvas绘制图片方法

    截至2022.12.23 修改日 微信小程序开发文档介绍不全,导致很多用户绘制图片不显示或失败,因此写下截至目前的可行方案 如果新手不熟悉canvas,先看下小程序官方文档 可运行案例: wxml: js:

    2024年02月12日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包