失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > cocos creator微信小游戏截图

cocos creator微信小游戏截图

时间:2023-07-12 14:20:50

相关推荐

cocos creator微信小游戏截图

前言

在之前,用CocosCreator制作的游戏,截图功能的实现是一个比较麻烦的地方,之前的官方文档也没有相关资料,只有论坛大神给出的一些解决方案。后来cocos更新了2.0版本,camera组件大改,截图功能也有了官方的解决方案,详情请见这里。不过本文讨论的不是h5或是原生平台,以上平台可以参考上面官方文档。

开始

微信小游戏其实已经给开发者准备了相关的截图api–Canvas.toTempFilePath,你们可以先进去看看文档关于各个参数的解释。这个函数的作用是,在当前的Canvas指定一个区域(没有参数情况下则截取整个Canvas)来截图,最后返回一个图片临时路径。根据不同的需求来使用函数返回的路径图片。

需求Ⅰ 预览所截的图,并保存图片

这里需要配合微信api的另一个函数wx.previewImage,同理可先进去看看文档怎么解释的。

wechat_download() {let canvas = cc.game.canvas;let rate = this.wechat_canvas.parent.width / canvas.width;let width = this.wechat_canvas.width / rate;let height = this.wechat_canvas.height / rate;canvas.toTempFilePathSync({x: canvas.width / 2 - this.wechat_canvas.width / rate / 2,y: canvas.height / 2 - (this.wechat_canvas.height / 2 + this.wechat_canvas.y) / rate,width: width,height: height,destWidth: width,destHeight: height,success : (res)=> {wx.previewImage({current: res.tempFilePath,urls: [res.tempFilePath]})}})},

上面是我调用的过程,其中要注意的是,不同设备适配的时候会将canvas拉伸,所以不可以直接用我们在cocos里的尺寸,这里我先计算放缩的比例rate,再根据rate调整截图位置和截图区域大小。

需求 Ⅱ 根据截图分享小游戏给好友

相关函数wx.shareAppMessage

shareFriend() {let canvas = cc.game.canvas;let rate = this.wechat_canvas.parent.width / canvas.width;let width = this.wechat_canvas.width / rate;let height = this.wechat_canvas.height / rate;canvas.toTempFilePathSync({x: canvas.width / 2 - this.wechat_canvas.width / rate / 2,y: canvas.height / 2 - (this.wechat_canvas.height / 2 + this.wechat_canvas.y) / rate,width: width,height: height,destWidth: 500,destHeight: 400,success: (res) => {wx.shareAppMessage({imageUrl: res.tempFilePath})}})},

使用方法其实和上面差不多,注意目标尺寸最好是5:4吧

总结

调用微信api的话截图比较简单,但需要注意位置的定位和canvas的转换,还有一点,上述转发图片功能我测试的时候,用游客appid是不能用的,所以需要自己去申请一个appid才能使用shareAppMessage函数。

如果觉得《cocos creator微信小游戏截图》对你有帮助,请点赞、收藏,并留下你的观点哦!

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