微信小程序--通过canvas生成图片并保存到本地

栏目: Html5 · 发布时间: 5年前

内容简介:需求场景:我们知道,微信小程序可以分享给好友或者微信群,不能分享到朋友圈,那分享到朋友圈就需要特殊处理一下,这里我们把小程序和通过canvasAPI绘制通过

需求场景:我们知道,微信小程序可以分享给好友或者微信群,不能分享到朋友圈,那分享到朋友圈就需要特殊处理一下,这里我们把小程序和 canvas 结合起来使用,生成自定义图片并保存到本地。

代码

  • wxml文件
<view>
    <button type="default" size="defaultSize" bindtap="exportImg">生成图片</button>
</view>
<canvas canvas-id="myCanvas"></canvas>
复制代码
  • js文件

通过canvasAPI绘制

const ctx = wx.createCanvasContext('myCanvas');
//绘制背景图
ctx.drawImage(res.path, 0, 0, screenWidth, 500);
//绘制背景图上层的头像
ctx.save();
ctx.arc(100, 100, 30, 0, 2 * Math.PI);
ctx.clip();
ctx.drawImage(avatarUrl, 50, 50, 110, 110);//根据微信getUserInfo接口获取到用户头像
ctx.restore();
//绘制文字
ctx.setTextAlign('center')
ctx.setFillStyle('#fff')
ctx.setFontSize(16)
ctx.fillText(userInfo.nickName, 100, 180)//用户昵称
ctx.stroke()
ctx.draw()
复制代码

通过 wx.canvasToTempFilePath 获取本地路径

wx.canvasToTempFilePath({
    x: 0,
    y: 0,
    width: 300,
    height: 500,
    canvasId: 'myCanvas',
    success: function (res) {
        console.log(res.tempFilePath);
    }
})
复制代码

通过 wx.saveImageToPhotosAlbum 保存图片到本地

wx.saveImageToPhotosAlbum({
    filePath: tempFilePath,//canvasToTempFilePath返回的tempFilePath
    success: (res) => {
        console.log(res)
    },
    fail: (err) => {}
})
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Understanding Machine Learning

Understanding Machine Learning

Shai Shalev-Shwartz、Shai Ben-David / Cambridge University Press / 2014 / USD 48.51

Machine learning is one of the fastest growing areas of computer science, with far-reaching applications. The aim of this textbook is to introduce machine learning, and the algorithmic paradigms it of......一起来看看 《Understanding Machine Learning》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具