天天看點

cocos creator使用頭條小遊戲相機功能作為背景cocos creator使用頭條小遊戲相機功能作為背景版本:2.4.2

cocos creator使用頭條小遊戲相機功能作為背景

版本:2.4.2

const { ccclass, property } = cc._decorator;

@ccclass
export default class TestVideo extends cc.Component {

    private camera: any = null;
    private video: any = null;
    private videoTexture: cc.Texture2D = null;
    @property(cc.Node)
    cameraNode:cc.Node = null;
    private frame: number = 0;

    onLoad() {
        this.startCamera();
    }

    startCamera() {
        console.log('startCamera')

        this.camera = tt.createCamera();
        tt.setKeepScreenOn();   // 保持螢幕常亮
        this.camera.start('front', true).then(video => {
            console.log('front')
            this.video = video;
            console.log('this.video='+JSON.stringify(this.video))

            this.initVideo();   // cocos視訊映射應該在camera初始完成之後
        }).catch(err => {
            tt.showToast({
                title: '錄影機需要授權'
            });
            console.log(err);
        });
        this.camera.setBeautifyParam(1, 1, 1, 1);   //設定美白、磨皮、大眼、瘦臉, 範圍:[0, 1]
    }

    initVideo() {

        console.log('initVideo')

        this.videoTexture = new cc.Texture2D();
        this.videoTexture.initWithElement(this.video);
        this.videoTexture.handleLoadedTexture();
        this.cameraNode.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(this.videoTexture);

        this.setVideoWidth(cc.view.getVisibleSize().width)  //固定寬度進行視訊縮放
        this.cameraNode.width = this.video.width;     //設定在遊戲界面畫的視訊寬度
        this.cameraNode.height = this.video.height;   //設定在遊戲界面畫的視訊高度

        console.log(`cameraNodewidth=${this.cameraNode.width} cameraNodeheight=${this.cameraNode.height}`)
        console.log(`videowidth=${this.video.width} videoheight=${this.video.height}`)

        this.cameraNode.rotation = -90
    }

    setVideoWidth(width: number) {
        if (this.video) {
            this.video.width = width;
            this.video.height = this.video.videoHeight / this.video.videoWidth * width;
        }
    }

    update(dt) {
        this.frame++;
        if (this.frame >= 5) {
            // this.startDetector();   //每五幀進行一次人臉檢測
            this.frame = 0
        }

        if (this.videoTexture && this.video) {
            // console.log('updatevideoTexture')
            this.videoTexture.update({
                image: this.video,
                flipY: true
            })
        }
    }

}