CocosCreator项目实战(14):功能-分享


一、主动分享

  1. 主动分享即在游戏中:1)点击排行榜后点击分享按钮;2)游戏结束后点击分享按钮。首先在game.jsproperties中添加两个按钮属性,并与Canvas绑定。
    properties: {
		...
        gameShareButton: cc.Button,
        rankShareButton: cc.Button,
    },
  1. onLoad()监听两个按钮,触发响应均为调用activeShare()方法。
    onLoad() {
		...
        this.gameShareButton.node.on('click', this.activeShare, this);
        this.rankShareButton.node.on('click', this.activeShare, this);
    },
  1. 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'),
        });
    },
  1. 在微信开发者工具中预览,可以看到游戏结束后点击分享,能完整显示分享的内容,包括标题与图片。

在这里插入图片描述


二、被动分享

  1. 被动分享即微信小游戏右上角菜单中自带的分享。默认是置灰的,因此在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'),
            }
        });
    },
  1. 在微信开发者工具中预览,可以看到游戏启动时控制台打印passive share!,并且点击小游戏右上角可以进行转发。

在这里插入图片描述


发布了102 篇原创文章 · 获赞 11 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/Fan0628/article/details/105030783