|
/**
|
* 截取指定节点
|
*/
|
cc.Class({
|
extends: cc.Component,
|
|
properties: {
|
screenshotNode: cc.Node,
|
iconSprite: cc.Sprite,
|
nameLabel: cc.Label,
|
scoreLabel: cc.Label,
|
newBestLabel: cc.Label,
|
scoreNumLabel: cc.Label,
|
|
isTakeScreenshot: false,
|
},
|
|
// LIFE-CYCLE CALLBACKS:
|
|
// onLoad () {
|
// if (this.isTakeScreenshot){
|
// cc.game.addPersistRootNode(this.node);
|
// }
|
// },
|
|
isFB() {
|
return typeof FBInstant !== 'undefined';
|
},
|
|
updateInfo(score, isNewBest, callback) {
|
this.nameLabel.string = this.isFB() ? FBInstant.player.getName() : 'Test Name';
|
this.newBestLabel.node.active = isNewBest;
|
this.scoreLabel.node.active = !isNewBest;
|
this.scoreNumLabel.string = score;
|
|
if (this.isFB()) {
|
cc.loader.load(FBInstant.player.getPhoto(), (err, texture) => {
|
if (!err) {
|
this.iconSprite.spriteFrame = new cc.SpriteFrame(texture);
|
if (this.isTakeScreenshot) {
|
callback && callback(this.toDataURL());
|
} else {
|
callback && callback(null);
|
}
|
} else {
|
callback && callback(null);
|
}
|
});
|
} else {
|
callback && callback(null);
|
}
|
},
|
|
toDataURL() {
|
this.screenshotNode.active = true;
|
let camera = this.screenshotNode.getComponent(cc.Camera);
|
|
let texture = new cc.RenderTexture();
|
let gl = cc.game._renderContext;
|
|
// 如果截图内容中不包含 Mask 组件,可以不用传递第三个参数
|
console.log('screen node width = ' + this.node.width + ' , height = ' + this.node.height);
|
texture.initWithSize(this.node.width, this.node.height, gl.STENCIL_INDEX8);
|
camera.targetTexture = texture;
|
camera.render();
|
|
// 这样我们就能从 RenderTexture 中获取到数据了
|
let data = texture.readPixels();
|
|
// 接下来就可以对这些数据进行操作了
|
let canvas = document.createElement('canvas');
|
let ctx = canvas.getContext('2d');
|
canvas.width = texture.width;
|
canvas.height = texture.height;
|
|
let width = texture.width;
|
let height = texture.height;
|
console.log('canvas width = ' + width + ' , height = ' + height);
|
|
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);
|
}
|
|
this.screenshotNode.active = false;
|
|
return canvas.toDataURL("image/jpeg");
|
}
|
|
// update (dt) {},
|
});
|