天天看點

Cocos Creator(2.x版本)螢幕截圖儲存分享)cocos creator 螢幕截圖 我用的是cocoscreator2.1.1版本

cocos creator (2.x版本)螢幕截圖儲存分享

  • cocos creator 螢幕截圖 我用的是cocoscreator2.1.1版本

cocos creator 螢幕截圖 我用的是cocoscreator2.1.1版本

直接上代碼

init() {
    let node = new cc.Node();
    node.parent = cc.director.getScene();
    let camera = this.camera

    // 設定你想要的截圖内容的 cullingMask
    // camera.cullingMask = 0xffffffff;

    // 建立一個 RenderTexture,并且設定 camera 的 targetTexture 為建立的 RenderTexture,這樣        camera 的内容将會渲染到建立的 RenderTexture 中。
    let texture = new cc.RenderTexture();
    this.texture = texture;
    let gl = cc.game._renderContext;

    // 如果截圖内容中不包含 Mask 元件,可以不用傳遞第三個參數
    texture.initWithSize(550, 550, gl.STENCIL_INDEX8);
    camera.targetTexture = texture;

    // 渲染一次錄影機,即更新一次内容到 RenderTexture 中
    camera.render();

    // 這樣我們就能從 RenderTexture 中擷取到資料了
    let data = texture.readPixels();

},

createSprite() {
    let width = this.texture.width;
    let height = this.texture.height;
    if (!this._canvas) {
        this._canvas = document.createElement('canvas');

        this._canvas.width = width;
        this._canvas.height = height;
    }
    let ctx = this._canvas.getContext('2d');
    this.camera.render();
    let data = this.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);
    }
    return this._canvas;
},

showFile(fileName) {
    //儲存的方法前端有很多,這裡暫時用這個

    let dataUrl = this._canvas.toDataURL("image/png");
    var img = new Image();
    img.src = dataUrl;
    let self = this;
    img.onload = function () {
        var texture = new cc.Texture2D();
        texture.initWithElement(img);
        texture.handleLoadedTexture();
        var newframe = new cc.SpriteFrame(texture);
        self.showL.spriteFrame = newframe;
    }
},


saveFile() {
    this._canvas.toTempFilePath({
        success: (res) => {
            wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,

                success(res) {
                    cc.log('儲存成功')
                },
                fail(res) {
                    cc.log('儲存失敗')
                }
            })
        }
    })
},
shareFunc() {
    let self = this;
    let dataUrl = this._canvas.toDataURL("image/png");
    try {
        this._canvas.toTempFilePath({
            x: 0,
            y: 55,
            width: 550,
            height: 440,
            success: (res) => {
                wx.shareAppMessage({
                    title: "****************",
                    imageUrl: res.tempFilePath,
                })
            }
        })

    } catch (error) {
        cc.log('不在微信平台');
    }

},
           

分享部分是直接把截圖分享到微信小遊戲的連結中