一、主动分享
- 主动分享即在游戏中:1)点击排行榜后点击分享按钮;2)游戏结束后点击分享按钮。首先在
game.js
的properties
中添加两个按钮属性,并与Canvas
绑定。
properties: {
...
gameShareButton: cc.Button,
rankShareButton: cc.Button,
},
- 在
onLoad()
监听两个按钮,触发响应均为调用activeShare()
方法。
onLoad() {
...
this.gameShareButton.node.on('click', this.activeShare, this);
this.rankShareButton.node.on('click', this.activeShare, this);
},
activeShare()方法
可参考微信官方文档,注意cc.url.raw()
中的资源路径需要有resources
,分享的图片需要放在...\2048\build\wechatgame\res\raw-assets\resources
目录下。
activeShare() {
console.log('active share!');
if (typeof wx === 'undefined') {
return;
}
wx.shareAppMessage({
title: '我玩了' + this.best + '分,你呢?',
imageUrl: cc.url.raw('resources/share.png'),
});
},
- 在微信开发者工具中预览,可以看到游戏结束后点击分享,能完整显示分享的内容,包括标题与图片。
二、被动分享
- 被动分享即微信小游戏右上角菜单中自带的分享。默认是置灰的,因此在
game.js
中添加passiveShare()方法
,并在onLoad()
中载入。passiveShare()方法首先调用wx.showShareMenu()
激活该按钮,然后调用wx.onShareAppMessage()方法
进行分享,可参考微信官方文档。
onLoad() {
...
this.passiveShare();
},
passiveShare() {
console.log('passive share!');
if (typeof wx === 'undefined') {
return;
}
wx.showShareMenu();
wx.onShareAppMessage(() => {
return {
title: '我玩了' + this.best + '分,你呢?',
imageUrl: cc.url.raw('resources/share.png'),
}
});
},
- 在微信开发者工具中预览,可以看到游戏启动时控制台打印
passive share!
,并且点击小游戏右上角可以进行转发。