当前位置:网站首页>Applet - canvas drawing Poster
Applet - canvas drawing Poster
2022-04-23 03:27:00 【Open the door of the world】
Demand background
Applets cannot be shared directly to the circle of friends , So use posters ( The key is the invitation code ) Invite friends .
From the display level , Just a few pictures , Put them together by positioning , But the key is to save , This is the time , Need canvas To synthesize pictures . that canvas Draw posters , Just split the two parts
adopt css , Combined pictures presented to users , It's as simple as
adopt css Layout , Put the elements together . Needless to say ,

When saving , adopt canvas mapping , Combine the picture into a complete picture
canvas mapping , There are two patterns
-
new edition 2d Pattern ( A pit , Use with caution )

-
Old version canvas-id=“drawPoster”, Although the operation is tedious , But compatibility is good

Get the picture size
downShareImage(imgurl) {
console.log('imgurl', imgurl);
return new Promise((resolve, reject) => {
wx.getImageInfo({
src: imgurl,
success: (res) => {
let {
width, height, path } = res;
resolve({
width,
height,
path,
});
},
fail: () => {
wx.showToast({
title: ' Download failed ',
icon: 'none',
});
reject(' Download failed ...');
},
});
});
},
canvas mapping
async drawPoster() {
const {
qrCodeImg, avatarImg, downImgRes, nickname } = this.data;
const ctx = wx.createCanvasContext('drawPoster');
ctx.drawImage(downImgRes.path, 0, 0, downImgRes.width, downImgRes.height);
const avatarImgW = 233;
const qrCodeW = 220;
const radius = 233 / 2;
let qrRadious = qrCodeW / 2;
let avX = downImgRes.width / 2 - avatarImgW + 120;
let avY = 100;
let qrX = downImgRes.width / 2 - qrCodeW + 110;
let qrY = 990;
ctx.save();
ctx.beginPath();
ctx.arc(avX + radius, avY + radius, radius, 0, 2 * Math.PI); // arc How to draw a curve , Calculate according to the coordinates of the center point , So add the radius
ctx.clip();
ctx.drawImage(avatarImg, avX, avY, 233, 233);
ctx.restore();
ctx.setFontSize(50);
ctx.setTextAlign('center');
ctx.setFillStyle('#7700d9');
ctx.fillText(nickname, downImgRes.width / 2, 415);
ctx.save();
ctx.arc(qrX + qrRadious, qrY + qrRadious, qrRadious, 0, 2 * Math.PI); // arc How to draw a curve , Calculate according to the coordinates of the center point , So add the radius
ctx.clip();
ctx.drawImage(qrCodeImg, qrX, qrY, 220, 220);
ctx.restore();
ctx.draw(false, async () => {
let canvasData = await this.exportPoster();
this.setData({
canvasData,
});
});
},
canvas Composite picture
exportPoster() {
return new Promise((resolve, reject) => {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 1061,
height: 1404,
canvasId: 'drawPoster',
fileType: 'png',
success(res) {
resolve(res.tempFilePath);
},
fail() {
wx.showToast({
title: ' Download failed ',
icon: 'none',
});
reject(' QR code generation failed ');
},
});
});
},
Long press save :
saveImage() {
const {
canvasData } = this.data;
if (!canvasData)
return wx.showToast({
title: ' Poster generation in progress ',
icon: 'none',
});
if (this.drawPosterLock) return;
this.drawPosterLock = true;
wx.saveImageToPhotosAlbum({
filePath: canvasData,
success: (res) => {
if (res.errMsg == 'saveImageToPhotosAlbum:ok') {
wx.showToast({
title: ' Saved successfully ',
});
}
},
complete: () => {
this.drawPosterLock = false;
},
fail: () => {
wx.showToast({
title: ' Save failed ',
icon: 'none',
});
},
});
},
Authorization logic
// Save as picture
handlerSavePhoto() {
let touchTime = this.data.touchEnd - this.data.touchStart;
console.log('touchTime', touchTime);
if (touchTime > 800) {
wx.getSetting({
success: (res) => {
var userPhotosAlbum = res.authSetting['scope.writePhotosAlbum'];
if (userPhotosAlbum) {
this.saveImage();
return;
}
if (userPhotosAlbum == undefined) {
// for the first time , Permission has never been requested
wx.authorize({
scope: 'scope.writePhotosAlbum',
success: (res) => {
if (res.errMsg == 'authorize:ok') {
// Click... In the authorization position pop-up box allow
this.saveImage();
}
},
});
return;
}
if (userPhotosAlbum != 'undefined') {
// The first authorization pop-up point is rejected Authorization is not allowed
wx.showModal({
title: ' Tips ',
content: ' There is no authority , Please open the permission ',
success: (res) => {
if (res.confirm) {
wx.openSetting({
success: (res) => {
if (res.authSetting['scope.writePhotosAlbum']) {
this.saveImage();
} else {
// unauthorized
}
},
});
}
},
});
}
},
});
}
},
summary :
- We're drawing canvas Always worry about size , And the drawing blur caused by size . Because the applet unit is rpx( Units adapted according to different models ), however canvas The drawing unit is px, Here's a good way .
- In fact, it is shown to users , It's just one. css Picture of layout , Use the units of the applet itself , Can solve the problem of different resolutions , And the rendering speed is very fast .
- When the user saves , What is kept is canvas drawing , Photos of composite pictures , Must be px, So you give canvas Wide and high , As long as it is consistent with the target diagram , Or double the size , All are ok Of
- Because drawing requires data , And it's asynchronous , Use await To do synchronization sequence
- utilize promise The package is beautiful
- use ctx.clip(); Cut the picture , Will destroy the current canvas environment , So you need to save the previous canvas environment first , Then start painting , After painting, restore the previous canvas environment
版权声明
本文为[Open the door of the world]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220619450882.html
边栏推荐
- Build websocket server in. Net5 webapi
- JSON related
- Learn about I / O flow and file operations
- 【VS Code】解决jupyter文件在vs code中显示异常的问题
- 2021-08-11
- Basic use of Charles
- “如何实现集中管理、灵活高效的CI/CD”在线研讨会精彩内容分享
- 2022 团体程序设计天梯赛 模拟赛 L2-1 盲盒包装流水线 (25 分)
- Initial experience of talent plan learning camp: communication + adhering to the only way to learn open source collaborative courses
- Charles uses three ways to modify requests and responses
猜你喜欢

Basic use of Charles

Learn about I / O flow and file operations

软件测试相关知识~

Unity Basics

When migrating tslib_ setup: No such file or directory、ts_ open: No such file or director

Super easy to use asynchronous export function of Excel

New ORM framework -- Introduction to beetlsql

Utgard connection opcserver reported an error caused by: org jinterop. dcom. common. JIRuntimeException: Access is denied. [0x800

2022 group programming ladder game simulation L2-4 Zhezhi game (25 points)

关于idea调试模式下启动特别慢的优化
随机推荐
oracle 查询外键含有逗号分隔的数据
第四次作业
MySQL installation pit
Redis(17) -- Redis缓存相关问题解决
List interface of collection
批量下载文件----压缩后再下载
Detailed explanation of socket programming send() and recv() functions
可以接收多種數據類型參數——可變參數
The query type of MySQL is very inefficient.
Flink real-time data warehouse project - Design and implementation of DWS layer
L3-011 direct attack Huanglong (30 points)
QT learning summary
poi根据数据创建导出excel
Translation of l1-7 matrix columns in 2022 group programming ladder Simulation Competition (20 points)
2022 团体程序设计天梯赛 模拟赛 L2-3 浪漫侧影 (25 分)
【VS Code】解决jupyter文件在vs code中显示异常的问题
[mock data] fastmock dynamically returns the mock content according to the incoming parameters
"Visual programming" test paper
Chapter 7 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of modular programming exercises with functions
Idempotency practice operation, explaining idempotency based on business