
const { ccclass, property } = cc._decorator;

@ccclass
export default class Home extends cc.Component {

    @property(cc.Camera)
    private camera: cc.Camera = null
    @property(cc.Sprite)
    private targetsp: cc.Sprite = null
    @property(cc.Sprite)
    private image: cc.Sprite = null


    renderTexture: cc.RenderTexture = null

    curr: number = 0
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start() {

    }

    // update (dt) {}

    onBtnClick() {
        cc.loader.loadRes("1_" + this.curr.toFixed(), cc.SpriteFrame, (err: Error, frame: cc.SpriteFrame) => {
            if (err) {
                cc.error(err)
            } else {
                this.image.spriteFrame = frame
                this.scheduleOnce(() => {
                    if (this.camera.targetTexture) {
                        this.camera.targetTexture.destroy()
                    }
                    this.renderTexture = new cc.RenderTexture();
                    this.renderTexture.packable = false
                    this.renderTexture.initWithSize(this.image.node.width, this.image.node.height, cc.gfx.RB_FMT_S8);
                    this.camera.targetTexture = this.renderTexture
                    this.scheduleOnce(() => {
                        this.camera.render(this.image.node);
                        let data = this.renderTexture.readPixels()
                        let targetTex = new cc.RenderTexture()
                        targetTex.packable = false
                        targetTex.initWithSize(580, 670)
                        targetTex.initWithData(Uint8Array.from(data), cc.Texture2D.PixelFormat.RGBA8888, 580, 670)
                        this.targetsp.spriteFrame = new cc.SpriteFrame(targetTex)
                    })
                })
            }
        })

        this.curr += 1
        this.curr = Math.round(this.curr % 3)
    }
}
