参考:
cocos版本:2.4.4
使用camera.targetTexture进行截图。
一 截图指定node
如下图,对heroNode进行截图。
MainScene.ts代码如下:
const { ccclass, property } = cc._decorator; @ccclass export default class MainScene extends cc.Component { @property(cc.Node) //截图目标节点 heroNode: cc.Node = null; start() { let node = this.screenShot(this.heroNode); node.x = 0; node.y = 0; node.parent = this.node; } /** * 截图 * @param targetNode 截图目标节点,如果为null则表示截全屏 * @returns 返回截屏图片的node */ screenShot(targetNode: cc.Node = null) { //获取当前场景Camera let camera = cc.director.getScene().getComponentInChildren(cc.Camera); //创建新的texture let texture = new cc.RenderTexture(); texture.initWithSize(cc.winSize.width, cc.winSize.height, (cc.game as any)._renderContext.STENCIL_INDEX8); //创建新的spriteFrame let spriteFrame = new cc.SpriteFrame(); if (targetNode == null) { spriteFrame.setTexture(texture); } else { let nodeX = cc.winSize.width / 2 + targetNode.x - targetNode.width / 2; let nodeY = cc.winSize.height / 2 + targetNode.y - targetNode.height / 2; let nodeWidth = targetNode.width; let nodeHeight = targetNode.height; //只显示node部分的图片 spriteFrame.setTexture(texture, new cc.Rect(nodeX, nodeY, nodeWidth, nodeHeight)); } //创建新的node let node = new cc.Node(); let sprite = node.addComponent(cc.Sprite); sprite.spriteFrame = spriteFrame; //截图是反的,这里将截图scaleY取反,这样就是正的了 sprite.node.scaleY = - Math.abs(sprite.node.scaleY); //手动渲染camera camera.cullingMask = 0xffffffff; camera.targetTexture = texture; camera.render(); camera.targetTexture = null; return node; } }
截图效果,可见人物只截取了node范围内的部分。
二 截图全屏
直接调用上面代码的screenShot(),不传入参数,就是截图全屏。
start() { let node = this.screenShot(); node.x = 0; node.y = 0; node.parent = this.node; }
截图了全屏