cocos creator (2.x版本)屏幕截图保存分享
cocos creator 屏幕截图 我用的是cocoscreator2.1.1版本
cocos creator 屏幕截图 我用的是cocoscreator2.1.1版本
直接上代码
init() {
let node = new cc.Node();
node.parent = cc.director.getScene();
let camera = this.camera
// 设置你想要的截图内容的 cullingMask
// camera.cullingMask = 0xffffffff;
// 新建一个 RenderTexture,并且设置 camera 的 targetTexture 为新建的 RenderTexture,这样 camera 的内容将会渲染到新建的 RenderTexture 中。
let texture = new cc.RenderTexture();
this.texture = texture;
let gl = cc.game._renderContext;
// 如果截图内容中不包含 Mask 组件,可以不用传递第三个参数
texture.initWithSize(550, 550, gl.STENCIL_INDEX8);
camera.targetTexture = texture;
// 渲染一次摄像机,即更新一次内容到 RenderTexture 中
camera.render();
// 这样我们就能从 RenderTexture 中获取到数据了
let data = texture.readPixels();
},
createSprite() {
let width = this.texture.width;
let height = this.texture.height;
if (!this._canvas) {
this._canvas = document.createElement('canvas');
this._canvas.width = width;
this._canvas.height = height;
}
let ctx = this._canvas.getContext('2d');
this.camera.render();
let data = this.texture.readPixels();
// write the render data
let rowBytes = width * 4;
for (let row = 0; row < height; row++) {
let srow = height - 1 - row;
let imageData = ctx.createImageData(width, 1);
let start = srow * width * 4;
for (let i = 0; i < rowBytes; i++) {
imageData.data[i] = data[start + i];
}
ctx.putImageData(imageData, 0, row);
}
return this._canvas;
},
showFile(fileName) {
//保存的方法前端有很多,这里暂时用这个
let dataUrl = this._canvas.toDataURL("image/png");
var img = new Image();
img.src = dataUrl;
let self = this;
img.onload = function () {
var texture = new cc.Texture2D();
texture.initWithElement(img);
texture.handleLoadedTexture();
var newframe = new cc.SpriteFrame(texture);
self.showL.spriteFrame = newframe;
}
},
saveFile() {
this._canvas.toTempFilePath({
success: (res) => {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
cc.log('保存成功')
},
fail(res) {
cc.log('保存失败')
}
})
}
})
},
shareFunc() {
let self = this;
let dataUrl = this._canvas.toDataURL("image/png");
try {
this._canvas.toTempFilePath({
x: 0,
y: 55,
width: 550,
height: 440,
success: (res) => {
wx.shareAppMessage({
title: "****************",
imageUrl: res.tempFilePath,
})
}
})
} catch (error) {
cc.log('不在微信平台');
}
},
分享部分是直接把截图分享到微信小游戏的链接中