Cocos Creator 2.0 实现截屏


const {ccclass, property} = cc._decorator;

//TS 脚本 会报红 不用管 可以运行   JS不会报错
@ccclass
export default class ScreenCaptureWindow extends cc.Component {

 
    capture () {

        //需要自己自行再创建一个 Camera depth要高于MainCamera 不然会黑屏 
        let camera=cc.find('Canvas/Camera').getComponent(cc.Camera);
        let texture = new cc.RenderTexture();
        texture.initWithSize(cc.visibleRect.width, cc.visibleRect.height);
        //cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888,0x88F0
        camera.targetTexture = texture;
        this.texture = texture;


        let width = this.texture.width;
        let height = this.texture.height;

        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        canvas.width = width;
        canvas.height = height;

        camera.render();
        let data = this.texture.readPixels();
        
        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);
        }

        var dataURL = canvas.toDataURL("image/jpeg");
        var img = document.createElement("img");
        img.src = dataURL;
        return img;
    }


    //需要截屏时 调用此方法
    captureAndShow () {
        var img = this.capture();

        // You can save the image or show it.

        // img.style.position = 'absolute';
        // img.style.display = 'block';
        // img.style.left = '0px'
        // img.style.top = '0px';
        // img.zIndex = 100;

        // img.style.transform = cc.game.container.style.transform;
        // img.style['transform-origin'] = cc.game.container.style['transform-origin'];
        // img.style.margin = cc.game.container.style.margin;
        // img.style.padding = cc.game.container.style.padding;

        // img.onclick = function (event) {
        //     event.stopPropagation();
        //     img.remove();
        // }

        // document.body.appendChild(img);

        let texture = new cc.Texture2D();
        texture.initWithElement(img);

        let spriteFrame = new cc.SpriteFrame();
        spriteFrame.setTexture(texture);

        let node = new cc.Node();
        node.parent = cc.director.getScene();
        node.zIndex = cc.macro.MAX_ZINDEX;

        let sprite = node.addComponent(cc.Sprite);
        sprite.spriteFrame = spriteFrame;
        
        node.x = cc.winSize.width/2;
        node.y = cc.winSize.height/2;
        //测试用 点击销毁图片
        node.on(cc.Node.EventType.TOUCH_START, () => {
            node.destroy();
        });
    }
    
}

 

 

 

你可能感兴趣的:(Cocos,Creator)