Cocos Creator 截屏方法 与 浏览器控制台打印图片方法

Cocos Creator 截屏方法

/**
 * cocos creater 截屏方法
 * @returns 图片
 */
function screenshot() {
  let node = cc.director.getScene().getChildByName("Canvas").getChildByName("screenshot");
  let camera = node?.getComponent(cc.Camera);
  if(!node){
    node = new cc.Node("screenshot");
    node.parent = cc.director.getScene().getChildByName("Canvas");
    camera = node.addComponent(cc.Camera);
  }

  // 设置你想要的截图内容的 cullingMask
  // camera.cullingMask = 0xffffffff;

  // 新建一个 RenderTexture,并且设置 camera 的 targetTexture 为新建的 RenderTexture,这样 camera 的内容将会渲染到新建的 RenderTexture 中。
  let texture = new cc.RenderTexture();
  texture.initWithSize(cc.visibleRect.width, cc.visibleRect.height);
  camera.targetTexture = texture;

  // 渲染一次摄像机,即更新一次内容到 RenderTexture 中
  camera.render();

  // 这样我们就能从 RenderTexture 中获取到数据了
  let data = texture.readPixels();

  // 接下来就可以对这些数据进行操作了
  let canvas = document.createElement("canvas");
  let ctx = canvas.getContext("2d");
  canvas.width = texture.width;
  canvas.height = texture.height;

  let width = texture.width;
  let height = texture.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 dataURL = canvas.toDataURL("image/jpeg");
  let img = document.createElement("img");
  img.src = dataURL;
  return img;
}

浏览器控制台打印图片方法

/**
 * 浏览器控制台打印图片
 * @param url 图片路径
 */
function setConsoleImage(url) {
  var img = new Image();
  img.style.display = "none";

  document.body.appendChild(img);
  img.src = url;
  img.onload = function () {
    var css = [
      "padding: " + (img.height / 2 - 8) + "px " + img.width / 2 + "px;",
      "line-height: " + img.height + "px;",
      "background-image: url(" + url + ");",
    ];
    console.log("%c ", css.join(""));
  };
}

你可能感兴趣的:(JavaScript,前端,javascript,前端,cocos,cocos-creator)