キャンバスを使用して次のレンダリングを実現します
- WeChat アプレットの公式キャンバス API を使用します。さらに詳しく知りたい場合は、参考ドキュメントを確認してください。ここでは繰り返しませんので、コードに直接進みます。
Canvas.wxml
<view>
<canvas class="firstCanvas _6a4ef3a" style="width:{
{windowWidth}}px;height:{
{windowHeight}}px;" canvas-id="firstCanvas" bindlongtap="generate"/>
</view>
キャンバス.js
let promiseAvatar=null; //定义暂存头像的function
const ctx = wx.createCanvasContext('firstCanvas'); //定义画图常量
Page({
/**
* 页面的初始数据
*/
data: {
windowHeight:0,
windowWidth:0
rate:0 //适配参数
},
methods:{
//获取设备参数
getWindowInfo() {
let {windowWidth,windowHeight} = wx.getSystemInfoSync();
let rate = windowWidth / 750;
this.setData({windowWidth,windowHeight,rate})
},
getUserAvatar(){
let userInfo=wx.getStorageSync('userInfo),
userAvatar=userInfo.avatarUrl,promiseAvatar;
return new Promise(function (resolve, reject) {
wx.getImageInfo({
src: userAvatar,
success: function (res) {
resolve(res);
},
fail: function (res) {
reject(res);
}
});
},
async drawImage(){
let {rate} = this.data;
let res = await getUserAvatar();
// 因为这个是其他的画报中截取的片段,所以这里要先保存一下
// 大致的实现步骤rate
// 绘制一个圆进行截切 ctx.clip()
// 最后填充图片
ctx.save(); //保存原有的画图
ctx.beginPath() //重新开始
ctx.arc( //绘制圆心坐标为(350,132),半径为66的圆
Math.floor(375 * rate),
Math.floor(132 * rate),
Math.floor(66 * rate),
0,
2 * Math.PI
);
ctx.clip() //裁剪
ctx.drawImage( //定位在圆圈范围内便会出现
res[0].path, //图片暂存路径
Math.floor(310 * rate),
Math.floor(66 * rate),
Math.floor(132 * rate),
Math.floor(132 * rate)
);
ctx.restore()
ctx.draw()
}
}
onShow(){
this.getWindowInfo();
this.drawImage();
}
})
画像について注意する必要があるのは、画像がネットワーク リソースの場合は、使用する前に画像を一時パスにダウンロードする必要があることです。wx.downloadFile メソッドを呼び出し、このメソッドによって返されたパスを使用して画像パスを描画します。 (ファイルのダウンロード ドメイン名は WeChat のバックグラウンドで設定する必要があります)