当前位置:网站首页>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
边栏推荐
- 【微服务】(十)—— 统一网关Gateway
- ThreadLocal 测试多线程变量实例
- Redis(17) -- Redis缓存相关问题解决
- 2022 group programming ladder game simulation L2-4 Zhezhi game (25 points)
- Using swagger in. Net5
- Visual programming -- how to customize the mouse cursor
- 幂等性实践操作,基于业务讲解幂等性
- Web Course Design - his system
- Code forces round # 784 (DIV. 4) solution (First AK CF (XD)
- Codeforces Round #784 (Div. 4)题解 (第一次AK cf (XD
猜你喜欢
Fiddler use
Utgard connection opcserver reported an error caused by: org jinterop. dcom. common. JIRuntimeException: Access is denied. [0x800
Explanation keyword of MySQL
A comprehensive understanding of static code analysis
12.<tag-链表和常考点综合>-lt.234-回文链表
Is it difficult to choose binary version control tools? After reading this article, you will find the answer
. net webapi access authorization mechanism and process design (header token + redis)
L3-011 direct attack Huanglong (30 points)
"Visual programming" test paper
Experiment 5 components and event handling
随机推荐
Configuration table and page information automatically generate curd operation page
New ORM framework -- Introduction to beetlsql
Unity Basics
A comprehensive understanding of static code analysis
场景题:A系统如何使用B系统的页面
Un aperçu des flux d'E / s et des opérations de fichiers de classe de fichiers
2022 团体程序设计天梯赛 模拟赛 L2-3 浪漫侧影 (25 分)
AWS from entry to actual combat: creating accounts
The website JS in. Net core cefsharp chromium WebBrowser calls the C method in winfrom program
Preview of converting doc and PDF to SWF file
Comprehensive calculation of employee information
2022 团体程序设计天梯赛 模拟赛 L2-1 盲盒包装流水线 (25 分)
浅学一下I/O流和File类文件操作
js 中,为一个里面带有input 的label 绑定事件后在父元素绑定单机事件,事件执行两次,求解
Basic use of Charles
Punch in: 4.22 C language chapter - (1) first knowledge of C language - (11) pointer
打卡:4.22 C语言篇 -(1)初识C语言 - (11)指针
Detailed explanation of socket programming send() and recv() functions
. net webapi access authorization mechanism and process design (header token + redis)
General testing technology [1] classification of testing