Draw local pictures using Canvas 2D API in applet

Original link: https://www.ixiqin.com/2022/07/29/in-a-small-program-used-in-the-canvas-api-to-draw-2-d-local-pictures/

6ee6df690137fd06bc6166adb63caca1.png

Since Applet 2.9.0, it is no longer recommended to use its own encapsulated Canvas Context. Instead, it is recommended that you use the standard Canvas 2D API to complete related operations. Therefore, for developers, it is necessary to adjust the past Canvas API to the new standard API.

It just so happened that I recently implemented a similar function and shared this part of the logic with you.

Page Layout

 <view> <view><button bindtap="chooseImage">选择图片</button></view> <view><canvas id="myCanvas" type="2d" style="background-color:gray;width: 100%;margin-top: 100rpx;"></canvas></view></view>

page logic

 Page({ chooseImage(){ // 创建一个Query const query = wx.createSelectorQuery() // 选中Canvas 对象query.select('#myCanvas') .fields({ node: true, size: true // 提取Node 信息}) .exec((res) => { // 获取到Canvas Node const canvas = res[0].node // 获取到Context const ctx = canvas.getContext('2d') wx.chooseMedia({ count: 1, success: function (res) { // 提取图片的基本信息wx.getImageInfo({ src: res.tempFiles[0].tempFilePath, success: imgInfo => { // 使用canvas.createImage 来创建一个图片const img = canvas.createImage() img.src = imgInfo.path img.onload = () => { // 将图片画在画布上ctx.drawImage(img, 0, 0, imgInfo.width, imgInfo.height) } } }) } }) }) }})

Reference documentation

This article is reprinted from: https://www.ixiqin.com/2022/07/29/in-a-small-program-used-in-the-canvas-api-to-draw-2-d-local-pictures/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment