preface

In the current of all kinds of small programs (WeChat, Baidu, Alipay), H5, NativeApp, we give you a strong multi-terminal development tool based on React: JD TARO (Taro · Alterman), TARO is committed to the unified solution of multi-terminal, one code, multiple operation.

Taro supports small programs with React, CSS preprocessor, real-time compilation and update, NPM, and more.

WeChat small program sharing picture function is often in the small program business, such as learning to punch share, promote member share, promote product share and so on. Because the small program does not support direct sharing of pictures to the circle of friends, the general operation is:

  1. Generate images containing small program code (or other specific information for the moment);
  2. Users click to save the picture, download to the local, and then publish to the circle of friends;
  3. Other users long press the identification of the small program code, into the current small program.

Hu elder brother to share with you today, based on TARO framework to achieve WeChat small program sharing picture function practice.

1. Build TARO project framework and create WeChat small program

1. Install TARO scaffolding tools

npm install -g @tarojs/cli

2. Initialize the TARO project

taro init taro-img-share

3. Compile the project, open the DEV mode, and generate a small program — dist directory

npm run dev:weapp

4. WeChat developer tool, create a small program, select the project root directory of taro-img-share under the dist directory

Second, small program sharing picture function practice — punch card picture sharing function

Picture first, then talk



This is the key point: use Canvas to draw pictures and display them, save them to the album

The drawImage() method draws the display, and the saveCard() method downloads the image to the album

src/pages/index/index.js

Import Taro, {Component} from '@tarojs/ Taro '// import Taro, {View, Text, Button, Canvas } from '@tarojs/components' import './index.scss' export default class Index extends Component { config = { } /** * constructor () {this.state = {userInfo: } /** * getUserInfo() getUserInfo(e) {if (! Return} this.setState({isShowCanvas: {isShowCanvas: {isShowCanvas: {isShowCanvas: {isShowCanvas:}); true, userInfo: e.detail.userInfo }, }} /** * DrawImage () {/** DrawImage () {/** DrawImage () {/** DrawImage () {/** DrawImage () {/** DrawImage () {/** DrawImage () Taro. CreateCanvasContext (' CardCanvas ') // let GRD = ctx. createInearGradient (0, 0, 1, 500) GRD. AddColorStop (0, FillRect (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) 500) // // Let {userInfo} = this.state let res = await Taro. DownloadFile ({url: userInfo.avatarUrl }) ctx.save() ctx.beginPath() // ctx.arc(160, 86, 66, 0, Math.PI * 2, false) ctx.arc(160, 88, 66, 0, Math.PI * 2) ctx.closePath() ctx.clip() ctx.stroke() ctx.translate(160, 88) ctx.drawImage(res.tempFilePath, -66, -66, Ctx. save() ctx. setfontSize (20) ctx.setFillStyle('#FFF') ctx.fillText(userInfo.NICKNAME, '#FFF') ctx.fillText(userInfo.NICKNAME, '#FFF') 100, 200) ctx.setFillStyle('black') ctx.fillText(' Black ') ctx.fillText(' Black ') ctx.fillText(' Black ') ctx.fillText(' Black ') 240) ctx.restore() // let qrcode = await Taro. DownloadFile ({url: "await Taro.") 'https://upload-images.jianshu.io/upload_images/3091895-f0b4b900390aec73.png?imageMogr2/auto-orient/strip%7CimageView2/2 /w/258/format/webp.jpg' }) ctx.drawImage(qrcode.tempFilePath, 70, 260, 180, } /** * saveCard() {/* async saveCard() {// Export the Canvas image content to the specified size of image let res = await  Taro.canvasToTempFilePath({ x: 0, y: 0, width: 400, height: 500, destWidth: 360, destHeight: 450, canvasId: 'cardCanvas', fileType: 'png' }) let saveRes = await Taro.saveImageToPhotosAlbum({ filePath: Res. TempFilePath}) if (saveRes errMsg = = = 'saveImageToPhotosAlbum: ok') {Taro. ShowModal ({title: 'images saved successfully, the content: ', showCancel: false, confirmText: 'confirm'})} else {Taro. ShowModal ({title: 'image failed to save ', content: 'Please try again! ', showCancel: false, confirmText: }} render () {let {isShowCanvas} = this.state return (<View className='index'> <Button) {let {isShowCanvas} = this.state return (<View className='index'> <Button) OngetUserInfo ={this.getUserInfo} opentType ="getUserInfo" type="primary" size="mini"> </Button> {/* Use Canvas to share image */} { isShowCanvas && <View className="canvas-wrap"> <Canvas id="card-canvas" className="card-canvas" style="width: 320px; height: 450px" canvasId="cardCanvas" > </Canvas> <Button onClick={this.saveCard} className="btn-save" type="primary" Size = "mini" > save the album < / Button > < / View >}}} < / View >)

src/pages/index/index.sass

CSS styles in the index.js component

.index { display: flex; align-items: center; justify-content: center; height: 100%; } .canvas-wrap { width: 100%; height: 100%; Background: rgba(0, 0, 0, 0.3); position: fixed; top: 0; left: 0; display: flex; align-items: center; justify-content: center; flex-direction: column; .btn-save { margin-top: 40rpx; }}

Matters needing attention

Set Taro to support async/await for ES6

  1. Download @ tarojs/async – await

    npm install -D @tarojs/async-await
  2. App. Introduced in js

    import '@tarojs/async-await'

Development is completed, release small program

  1. Execute packaging, generate the final small program source code

    npm run build:weapp
  2. Release applet

    Click the WeChat Developer Tools Upload button, upload the applet, and then publish the applet in the WeChat applet platform.

summary

  1. This paper focuses on the use of TARO to achieve small program generation card picture, save the album, share the picture function of the development principle and practical steps, you children’s shoes can refer to and combined with their own actual business expansion development.
  2. In this paper, for in-depth picture adaptation of different mobile phones, some values are also set as fixed values (such as the starting coordinate of the text filling and the length and size of the text filling), and no proportional response is made. For those who need further communication, you can pay attention to the official account of Hu Ge Youhua, continue to pay attention to the relevant articles, or leave a message to communicate directly in the article.
  3. No matter what framework is used such as Taro, mpvue, wepy, etc. to develop a small program to share the image function, the principle is the same, but in the call method and processing logic need to respond to small adjustments

Grasp the principle of business function realization, is the magic weapon to win everything!

How do I get the source code for this example

  1. Pay attention to Hu elder brother has words public number
  2. Respond to the keyword TARO, you will receive the project source address

Afterword.

The above is the content that Hu Ge shared with you today, like small friends remember to collect, forward, click the button in the lower right corner to see, recommend to more small friends Yo, welcome to leave a message to communicate…

Hu elder brother has words, a technology, have feelings of Hu elder brother! Jingdong open platform chief front-end siege lion. Talk with you about the big front end, share the front end system architecture, framework implementation principle, the latest and most efficient technical practice!

Long press sweep code attention, more handsome more beautiful yo! Pay attention to the words of elder brother Hu public number, can continue to in-depth exchanges with elder brother Hu yo!