


Take you step by step to implement the function of saving picture components in the mini program
Oct 27, 2021 am 10:46 AMThis article will let you talk aboutWeChat appletSave picture component development, I hope it will be helpful to everyone!
Many WeChat mini programs allow users to share activities by saving posters to let more people know about their mini programs. I must have encountered this when developing mini programs. Bar. [Related learning recommendations: 小program development tutorial]
Today I will share the function of saving posters in a small program I made in the company. First, let me first describe what the needs were like in the company before. The company's online mini program will have a long-term purpose of promoting new users. Each user must have a poster of their own, and promotion through personal posters is just a simple way.
After receiving the task, I also went to Universal Internet to do research first, but my senior brother told me that he had done something similar to this, but at that time it was just to complete the task, so the code was very messy, and then he started from other projects. I searched and searched for the code, and finally found it for me~~~ But the time given to me was tight and the task was heavy, so I had to make some adjustments and submit it first. After that, I followed the online articles and followed the pitfalls step by step, and implemented a component for saving posters step by step.
Thoughts
First of all, let’s declare that the component uses uniapp, which specifically implements the basic functions of drawing pictures, drawing text, and saving posters to albums. These are fully sufficient during development. used.
Draw the poster through canvas. Use uni.canvasToTempFilePath
to convert the drawn canvas into a picture. Use uni.saveImageToPhotosAlbum
to save the pictures in the local temporary path to the mobile phone album. My idea is to encapsulate all the methods used into components, and only use the parent component to call the methods that need to be used and adjust the relevant parameters. For specific usage, you can view the sample code
The order of drawing poster content through canvas
Determine the order of drawing poster content by using the promise object. promise.all()
Method performs the last step of canvas painting operation context.draw()
Note uni.getImageInfo()
When drawing pictures and avatars, the component obtains the relevant information of the picture through
uni.getImageInfo()
. The prerequisite for successful calling of this method is that the download domain name and request domain name need to be configured in the WeChat applet background. Of course, it is best to configure the uploadFile domain name together to prevent errors. However, the official tip is to configure the download domain name whitelist, but the image information cannot be obtained, which is a big pitfall.If there is no relevant configuration, the vconsole debugging tool is opened during debugging or trial version, official version, etc. uni.getImageInfo() can obtain image information. Once vconsole is closed, uni.getImageInfo() will fail, which is also a pitfall.
This component method, variable introduction
props
-
canvasInfo Object (required)
canvasWidth canvas width
canvasHeight canvas height
canvasId canvas identification
-
isFullScreen Boolean
When it is true, it means that the canvas is the full screen of the mobile phone screen, and the width and height set by canvasInfo will be invalid.
Default is false
methods
canvasInit(callback) Canvas initialization, all canvas operations must be performed in its callback function.
drawCanvasImage(context, src, _imageWidth, _imageHeight, dx, dy) Draw an image on canvas
drawCircularAvatar(context, url, _circularX, _circularY, _circularR) Draw a circular picture on canvas
- ##drawText(options) Draw single or multi-line text on canvas
- startDrawToImage(context, promiseArr, callback) Draw() on canvas
- posterToPhotosAlbum(filePath) Save to mobile phone album
<template>
<view>
<view class="savePosterItem">
<image v-show="tempFilePath" :src="tempFilePath"></image>
<save-poster-com v-show="!tempFilePath" ref="savePoster" :canvasInfo="canvasInfo"></save-poster-com>
</view>
<button class="savePosterBtn" type="primary" @click="saveBtnFun">保存海報(bào)</button>
</view>
</template>
<script>
import SavePosterCom from '@/components/SavePosterCom/SavePosterCom.vue'
export default {
components: {
SavePosterCom
},
data() {
return {
canvasInfo: {
canvasWidth: 620,
canvasHeight: 950,
canvasId: 'save-poster'
},
tempFilePath: '',
canvasBgUrl: 'https://images.pexels.com/photos/4065617/pexels-photo-4065617.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500',
avatarUrl: 'https://p9-passport.byteacctimg.com/img/user-avatar/4dbf31fa6dec9c65b78a70d28d843c04~300x300.image'
}
},
onLoad() {
let {
drawCanvasImage,
drawCircularAvatar,
drawText
} = this.$refs.savePoster.$options.methods
this.$refs.savePoster.canvasInit(({
context,
comThis
}) => {
// 獲取畫布寬高
let canvasWH = comThis.canvasWH
// 繪制海報(bào)背景圖
let promise_1 = drawCanvasImage(context, this.canvasBgUrl, canvasWH.canvasWidth, canvasWH.canvasHeight)
// 必須先繪制玩海報(bào)背景圖 再去操作其他繪制內(nèi)容
promise_1.then(res => {
let promise_2 = drawCircularAvatar(context, this.avatarUrl, canvasWH.canvasWidth / 2, canvasWH.canvasHeight /
7, 70)
let promise_3 = drawText({
context: context,
text: '皮皮蝦仁',
dx: (canvasWH.canvasWidth / 2) + 60,
dy: canvasWH.canvasHeight / 4,
fontSize: 30,
fontColor: '#5D4037'
})
let promise_4 = drawCanvasImage(context, this.avatarUrl, 150, 150, (canvasWH.canvasWidth / 2) + 85, (canvasWH.canvasHeight -
165))
this.$refs.savePoster.startDrawToImage(context, [promise_1,promise_2,promise_4], (tempFilePath) => {
this.tempFilePath = tempFilePath
})
})
})
},
methods: {
saveBtnFun() {
uni.showModal({
title: '保存海報(bào)',
content: '海報(bào)將被保存至相冊(cè)中',
confirmText: '保存',
success: (res) => {
if(res.confirm) {
this.$refs.savePoster.posterToPhotosAlbum(this.tempFilePath)
}
}
})
}
}
}
</script>
<style>
.savePosterItem {
text-align: center;
}
.savePosterItem > image {
width: 620rpx;
height: 950rpx;
}
.savePosterBtn {
margin-top: 40rpx;
width: 80%;
}
</style>
Component source code<template>
<view>
<canvas :canvas-id="canvasInfo.canvasId" :style="{width: canvasWH.canvasWidth + 'px', height: canvasWH.canvasHeight + 'px'}"></canvas>
</view>
</template>
<script>
export default {
name: 'savePosterCom',
data() {
return {
userPhoneWHInfo: {},
canvasWH: {
canvasWidth: 0,
canvasHeight: 0
}
}
},
props: {
// 決定保存下來(lái)的圖片的寬高
canvasInfo: {
type: Object,
default: () => {
return {
canvasWidth: 0,
canvasHeight: 0,
canvasId: 'canvasId'
}
}
},
// canvas畫布是不是全屏,默認(rèn)是false。 false時(shí)使用必須傳 canvasInfo
isFullScreen: Boolean
},
created() {
this.userPhoneWHInfo = this.getPhoneSystemInfo()
if (this.isFullScreen) { // 畫布全屏
this.canvasWH.canvasWidth = this.userPhoneWHInfo.windowWidth
this.canvasWH.canvasHeight = this.userPhoneWHInfo.windowHeight
} else { // 指定寬高
this.canvasWH.canvasWidth = this.canvasInfo.canvasWidth
this.canvasWH.canvasHeight = this.canvasInfo.canvasHeight
}
},
mounted() {},
methods: {
/**
* 獲取用戶手機(jī)屏幕信息
*/
getPhoneSystemInfo() {
const res = uni.getSystemInfoSync();
return {
windowWidth: res.windowWidth,
windowHeight: res.windowHeight
}
},
/** 獲取 CanvasContext實(shí)例
* @param {String} canvasId
*/
getCanvasContextInit(canvasId) {
return uni.createCanvasContext(canvasId, this)
},
/** 保存海報(bào)組件初始化
* @param {Function} callback(context) 回調(diào)函數(shù)
*/
canvasInit(callback) {
let context = this.getCanvasContextInit(this.canvasInfo.canvasId)
if (context) {
callback({
context: context,
comThis: this
})
}
},
/** 將上訴的繪制畫到畫布中 并且 將畫布導(dǎo)出為圖片
* @param context 畫布
* @param {Promise[]} 存放Promise的數(shù)組
* @param {Function} callback 保存圖片后執(zhí)行的回調(diào)函數(shù)(本地圖片臨時(shí)路徑)
*/
startDrawToImage(context, promiseArr, callback) {
// 將之前在繪圖上下文中的描述(路徑、變形、樣式)畫到 canvas 中
let canvasId = this.canvasInfo.canvasId
let tempFilePath = ''
Promise.all(promiseArr).then(res => {
context.draw(false, async () => {
callback(await this.canvasToImage(canvasId))
})
})
},
/**
* 在canvas繪制一張圖片
* @param context 畫布
* @param src 圖片資源
* @param _imageWidth 圖片寬度
* @param _imageHeight 圖片高度
*/
drawCanvasImage(context, src, _imageWidth, _imageHeight, dx, dy) {
return new Promise((resolve, reject) => {
uni.getImageInfo({
src: src,
success: res => {
context.drawImage(res.path, (dx - _imageWidth), (dy - _imageHeight), _imageWidth, _imageHeight)
resolve(context)
},
})
})
},
/** 繪制一個(gè)圓形頭像
* @param context 畫布
* @param url 圖片地址
* @param _circularX 圓心X坐標(biāo)
* @param _circularY 圓心Y坐標(biāo)
* @param _circularR 圓半徑
*/
drawCircularAvatar(context, url, _circularX, _circularY, _circularR) {
let dx = _circularX - _circularR;
let dy = _circularY - _circularR;
let dwidth = _circularR * 2;
let dheight = _circularR * 2
return new Promise((resolve, reject) => {
uni.downloadFile({
url: url,
success: res => {
context.save()
context.beginPath()
// _circularX圓的x坐標(biāo) _circularY圓的y坐標(biāo) _circularR圓的半徑
context.arc(_circularX, _circularY, _circularR, 0, 2 * Math.PI)
context.clip()
// dx: 圖像的左上角在目標(biāo)canvas上 X 軸的位置
// dy: 圖像的左上角在目標(biāo)canvas上 Y 軸的位置
// dwidth: 在目標(biāo)畫布上繪制圖像的寬度,允許對(duì)繪制的圖像進(jìn)行縮放
// dheight: 在目標(biāo)畫布上繪制圖像的高度,允許對(duì)繪制的圖像進(jìn)行縮放
context.drawImage(res.tempFilePath, dx, dy, dwidth, dheight)
context.restore()
// context.draw()
resolve(context)
}
})
})
},
/** 繪制多行文本 注:, 和 空格都算一個(gè)字
* @param context 畫布
* @param text 需要被繪制的文本
* @param dx 左上角x坐標(biāo)
* @param dy 右上角y坐標(biāo)
* @param rowStrnum 每行多少個(gè)字 (默認(rèn)為text字體個(gè)數(shù)->單行)
* @param fontSize 文字大小 (默認(rèn)16)
* @param fontColor 文字顏色 (默認(rèn)black)
* @param lineHeight 單行文本行高 (默認(rèn)0)
*/
drawText(options) {
let {
context,
text,
dx,
dy,
rowStrnum = text.length,
lineHeight = 0,
fontSize = 16,
fontColor = 'black'
} = options
return new Promise((resolve, reject) => {
context.setFontSize(fontSize)
context.setFillStyle(fontColor)
context.setTextBaseline('middle')
// 獲取需要繪制的文本寬度
let textWidth = Number(context.measureText(text).width)
// console.log('textWidth',textWidth)
// 獲取文本的字?jǐn)?shù)
let textNum = text.length
// 獲取行數(shù) 向上取整
let lineNum = Math.ceil(textNum / rowStrnum)
// console.log('textNum',textNum)
// console.log('lineNum',lineNum)
for (let i = 0; i < lineNum; i++) {
let sliceText = text.slice(i * rowStrnum, (i + 1) * rowStrnum)
// fillText 的 dx = 文字最左邊的距離到屏幕政策的距離
context.fillText(sliceText, dx - textWidth, dy + i * lineHeight);
}
resolve(context)
})
},
/** 將畫布導(dǎo)出為圖片
* @param canvasId 畫布標(biāo)識(shí)
*/
canvasToImage(canvasId) {
return new Promise((resolve, reject) => {
uni.canvasToTempFilePath({
canvasId: canvasId, // 畫布標(biāo)識(shí)
success: res => {
// 在H5平臺(tái)下,tempFilePath 為 base64
resolve(res.tempFilePath)
},
fail: err => {
console.log('err', err)
reject(err)
}
}, this)
})
},
/** 保存生成的圖片到本地相冊(cè)中
* @param {String} filePath 圖片臨時(shí)路勁
*/
posterToPhotosAlbum(filePath) {
console.log('filePath',filePath)
uni.showLoading({
title: '保存中...'
})
uni.saveImageToPhotosAlbum({
filePath: filePath,
success: (res) => {
uni.showToast({
title: '保存成功,請(qǐng)前往手機(jī)相冊(cè)中查看',
mask: true,
icon: 'none',
duration: 2000
})
},
fail: (err) => {
console.log('err',err)
if (err.errMsg.includes('deny')||err.errMsg.includes('denied')) { // 用戶選擇拒絕
this.openSetting()
} else if (err.errMsg.includes('fail cancel')) { // 用戶在保存圖片時(shí) 取消了
uni.showToast({
title: '已取消保存,無(wú)法保存至相冊(cè)',
mask: true,
icon: 'none',
duration: 2000
})
return
}
},
complete: () => {
uni.hideLoading()
}
})
},
/**
* 打開攝像頭設(shè)置權(quán)限頁(yè)面
*/
openSetting() {
uni.showModal({
title: '溫馨提示',
content: '保存圖片至相冊(cè)中,需要您同意添加訪問(wèn)相冊(cè)權(quán)限',
cancelText: '拒絕',
confirmText: '同意',
success: res => {
if (res.confirm) {
uni.openSetting({
success: settingdata => {
if (settingdata.authSetting['scope.writePhotosAlbum']) {
console.log('獲取權(quán)限成功,給出再次點(diǎn)擊圖片保存到相冊(cè)的提示。')
uni.showToast({
title: '授權(quán)成功,請(qǐng)?jiān)俅吸c(diǎn)擊保存',
icon: 'none',
duration: 2000,
})
} else {
console.log('獲取權(quán)限失敗,給出不給權(quán)限就無(wú)法正常使用的提示')
uni.showToast({
title: '需要訪問(wèn)相冊(cè)權(quán)限',
icon: 'none',
duration: 2000,
})
}
},
fail: (res) => {
console.log('err', err)
}
})
} else {
uni.showToast({
title: '已拒絕授權(quán),無(wú)法保存至相冊(cè)',
mask: true,
icon: 'none',
duration: 2000
})
return
}
}
})
}
}
}
</script>
<style>
</style>
Effect
##For more programming-related knowledge, please visit:
The above is the detailed content of Take you step by step to implement the function of saving picture components in the mini program. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include
