5

在小程序中使用的 Canvas 2D API 绘制本地图片

 3 years ago
source link: https://www.ixiqin.com/2022/07/29/in-a-small-program-used-in-the-canvas-api-to-draw-2-d-local-pictures/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

6ee6df690137fd06bc6166adb63caca1-624x266.png

在小程序中使用的 Canvas 2D API 绘制本地图片

小程序自 2.9.0 起,不再推荐使用其自己封装的 Canvas Context,而是更加推荐大家使用标准的 Canvas 2D API 来完成相关操作。因此,对于开发者来说,需要将过去的 Canvas API 调整为新的标准的 API 。

刚好我最近也实现了类似的功能,将这部分逻辑分享给大家。

<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({
   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)
                }
              }
            })
          }
        })
      })
   }
})

本条目发布于2022年7月29日。属于小程序分类,被贴了 Canvas小程序 标签。

← WordPress 出现 RedisException: OOM command not allowed when used memory > ‘maxmemory’ 的报错怎么处理? 使用小程序的 Canvas 2D 提取特定点的颜色 →

发表回复 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

评论 *

显示名称 *

电子邮箱地址 *

网站地址

在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。

如果有人回复我的评论,请通过电子邮件通知我。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK