100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 微信小程序使用html2canvas 微信小程序canvas 2d 引入本地图片并生成分享图

微信小程序使用html2canvas 微信小程序canvas 2d 引入本地图片并生成分享图

时间:2020-07-27 12:18:19

相关推荐

微信小程序使用html2canvas 微信小程序canvas 2d 引入本地图片并生成分享图

在小程序基础库 v2.9.0 正式开放一套全新的 Canvas 接口。该接口符合 HTML Canvas 2D 的标准,实现上采用 GPU 硬件加速,渲染性能相比于现有的 Canvas 接口有一倍左右的提升。

接口用法可参考该代码片段。

本文在此代码片段上做了点调整,来实现引入本地图片并生成分享图

index.wxml

index.js

const app = getApp()

Page({

data: {

},

onLoad: function () {

const query = wx.createSelectorQuery();//如果是在组件中,则改成 this.createSelectorQuery()

query.select('#canvas').fields({

node: true,

rect: true

}, res => {

const canvas = res.node;

const ctx = canvas.getContext('2d');

canvas.width = 500;//本地图像的width

canvas.height = 753;//本地图像的height

this.render(canvas, ctx);

}).exec()

},

render(canvas, ctx) {

let that = this;

let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象

img.onload = (e) => {

console.log('img loaded')

ctx.drawImage(img, 0, 0, 500, 753);

ctx.font = "28px sans-serif";

ctx.fillStyle = "rgba(0, 0, 0, 1)";

ctx.fillText("我是分享文字111111111", 0, 40);

ctx.fillStyle = "rgba(0, 0, 0, .5)";

ctx.fillText("我是分享文字222", 0, 80);

wx.canvasToTempFilePath({

canvas,

wwidth: 500,

height: 753,

destWidth:500,

destHeight:753,

success(res) {

console.log(res.tempFilePath)

that.setData({

imgSrc:res.tempFilePath

})

}

}, that)

}

img.onerror = (e) => {

console.error('err:', e)

}

img.src = './share.jpg'

},

})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。