相关
原理: 摄像机 + RenderTexture
目标平台:Cocos Creator 2.4.x
截图效果:
使用方法:
1.添加分组
2.添加次要相机,并设置数据
3.使用 可以修改摄像机的相关属性,获取想要的数据。
/**
* 截图
* @param { 摄像机x坐标 } x
* @param { 摄像机y坐标 } y
* @param { 视图大小 } orthosize
* @param { 生成截图宽 } width
* @param { 生成截图高 } height
* @returns base64
*/
_screenshot(CameraX, CameraY, orthosize, width, height) {
let nodeCamera = cc.find('Canvas/Secondary Camera');
nodeCamera.x = CameraX;
nodeCamera.y = CameraY;
let camera = nodeCamera.getComponent(cc.Camera);
// 背景颜色
// camera.backgroundColor = cc.Color.TRANSPARENT
// 清除标记
// camera.clearFlags = cc.Camera.ClearFlags.DEPTH | cc.Camera.ClearFlags.STENCIL | cc.Camera.ClearFlags.COLOR
// 遮罩层级 默认为 Everything,表明渲染所有层的物体。
camera.cullingMask = ~(1 << 1);
camera.orthoSize = orthosize;
// 定义
let texture = new cc.RenderTexture();
texture.initWithSize(width, height);
// 设置 targetTexture
camera.targetTexture = texture;
// 重新渲染摄像机
camera.render();
// 从 RenderTexture 中读取像素数据
let pixels = new Uint8Array(width * height * 4);
let x = texture.width / 2 - width / 2;
let y = texture.height / 2 - height / 2;
let w = width;
let h = height;
let data = texture.readPixels(pixels, x, y, w, h);
// 操作数据
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
// 写入数据
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);
}
let base64 = canvas.toDataURL('image/png');
console.log(base64);
return base64;
}
源码地址
遇到的问题:
1. TypeError: cc.RenderTexture is not a constructor
原因与解决方案:
1. RenderTexture 模块未选择; 勾选 “项目 -> 项目设置 -> 模块设置” 面板中的 RenderTexture 模块(自行翻译吧,加深记忆! Render textures are textures that can be rendered to. )
附加:
摄像机属性
-
backgroundColor:背景颜色,当指定了摄像机需要清除颜色的时候,摄像机会使用设定的背景色来清除场景。特别提醒一下,可以设置为透明 cc.Color.TRANSPARENT;
-
depth:深度,用于决定摄像机的渲染顺序。值越大,则摄像机越晚被渲染;
-
cullingMask:遮罩层级 ,默认 everying。用于决定摄像机渲染场景的哪些部分,可在属性面板上勾选。与碰撞分组相同,最大32个分组;
-
clearFlags:清除操作,渲染摄像机时需要做的清除操作;
-
rect:区域,摄像机绘制的区域;
-
zoomRatio:缩放比例,指定摄像机缩放比例值越大显示图像越大;
-
alignWithScreen:自动调整到屏幕大小,也可选择手动控制;
-
orthoSize:视图大小,上个选项为false时,该属性生效;
-
targetTexture: 如果设置 targetTexture,摄像机渲染的内容将不会在输出到屏幕。
cullingMask 使用技巧:
// 当相机everything 时,cullingMask 为 -1,即32个1,0xffffffff;
// 当相机nothing 时,cullingMask 等于 0;
// 渲染除去层x的所有层
camera.cullingMask = ~(1 << x);
// 关闭(减掉)层 x
camera.cullingMask &= ~(1 << x);
// 打开(增加)层 x
camera.cullingMask |= (1 << x);
// 摄像机只显示第x层, y层, z层.
camera.cullingMask = (1 << x) + (1 << y) + (1 << z);
还不懂得就去复习 位运算符 吧!!!