参考博客 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;