cocos creator单节点截图

参考博客 https://xmanyou.com/cocos-creator-2-2-0-jie-tu-chu-xian-yi-chang-hei-se-bei-jing/

正确截图并不需要不开启3D功能

1). 如果是全屏的截图,则继续沿用的旧的代码,直接将RenderTexture的size设置为屏幕大小即可。
2). 如果是截取特定范围内的内容,
首先,RenderTexture使用屏幕尺寸
其次,只读取RenderTexture指定范围的像素点
最后,将像素信息转换为Image

完整代码如下:

let texture = new cc.RenderTexture();
        texture.initWithSize(cc.visibleRect.width, cc.visibleRect.height, cc.gfx.RB_FMT_S8);
        this.camera.targetTexture = texture;

        let width = this.capNode.width;
        let height = this.capNode.height;
        this._canvas = document.createElement('canvas');

        this._canvas.width = width;
        this._canvas.height = height;
        
        let ctx = this._canvas.getContext('2d');
        this.camera.render();

        // 2. 获取指定区域的像素点信息
        let size = this.capNode.getContentSize();
        let pixels = new Uint8Array(size.width * size.height * 4);
        let x = texture.width/2 - this.capNode.width/2;
        let y = texture.height/2 - this.capNode.height/2;
        let w = this.capNode.width;
        let h = this.capNode.height;
        let data = texture.readPixels(pixels, x, y, w, h);

        // let data = texture.readPixels();
        
        // write the render data
        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 = this._canvas.toDataURL("image/png");
            var img = document.createElement("img");
            img.src = dataURL;  

            cc.log(dataURL)

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

            let sf = new cc.SpriteFrame();
            sf.setTexture(texture2);

            this.laodSpr.spriteFrame=sf;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值