cocos creator 小游戲區域截圖功能實現

来源:https://www.cnblogs.com/hutuzhu/archive/2019/07/24/11234136.html
-Advertisement-
Play Games

截圖是游戲中非常常見的一個功能,在cocos中可以通過攝像機和 RenderTexture 可以快速實現一個截圖功能,具體API可參考:https://docs.cocos.com/creator/manual/zh/render/camera.html?h=%E6%88%AA%E5%9B%BE,其 ...


截圖是游戲中非常常見的一個功能,在cocos中可以通過攝像機和 RenderTexture 可以快速實現一個截圖功能,具體API可參考:https://docs.cocos.com/creator/manual/zh/render/camera.html?h=%E6%88%AA%E5%9B%BE,其中官方也提供了比較完整的例子。

實際上不用官網提供的全屏截圖的例子,一般在網頁中我們也能將頁面截圖保存,比如通過htmltocanvas,cocos開發的小游戲在網頁中打開實際就是一個canvas,前端是可以通過將canvas保存為圖片的,這裡就不細說了。

我們還是來看下如何把屏幕中某一區域的內容生成圖片並保存到本地。

1、創建RenderTexture

//新建一個 RenderTexture,並且設置 camera 的 targetTexture 為新建的 RenderTexture,這樣 camera 的內容將會渲染到新建的 RenderTexture 中。
let texture = new cc.RenderTexture();
let gl = cc.game._renderContext;
//如果截圖中不含mask組件可以不加第三個參數,不過建議加上 texture.initWithSize(this.node.width, this.node.height, gl.STENCIL_INDEX8);//這裡的寬高直接決定了截圖的寬高,如果是全屏截圖就是cc.visibleRect.width, cc.visibleRect.height,該處可以設置為截圖目標區域的寬高
this.camera = this.node.addComponent(cc.Camera); this.camera.targetTexture = texture; this.texture = texture;

 2、繪製canvas

createSprite() {
        let width = this.texture.width;
        let height = this.texture.height;
     //截圖的本質是創建一個canvas,然後通過canvas生成圖片材質
if (!this._canvas) { this._canvas = document.createElement('canvas'); this._canvas.width = width; this._canvas.height = height; } else { this.clearCanvas(); } let ctx = this._canvas.getContext('2d'); this.camera.render();//相機繪製,將屏幕上的內容更新到renderTexture中 let data = this.texture.readPixels();//讀取renderTexture中的數據 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; },

上述代碼中用到了canvas 的createImageData() 和putImageData()方法,createImageData() 方法創建新的空白 ImageData 對象,putImageData() 方法將圖像數據(從指定的 ImageData 對象)放回畫布上。

3、獲取圖片

initImage(img) {
        // return the type and dataUrl
        var dataURL = this._canvas.toDataURL("image/png");
        var img = document.createElement("img");
        img.src = dataURL;
        return img;
},

生成canvas就可以通過canvas.toDataURL()方法將canvas轉換為圖片

4、生成截圖效果,將上一步生成的圖片當做材質掛載到新建的node

showSprite(img) {
        let y = this.getTargetArea().y;
        let x = this.getTargetArea().x;
        let rect = new cc.Rect(x, y, 770, 800)
        let texture = new cc.Texture2D();
        texture.initWithElement(img);

        let spriteFrame = new cc.SpriteFrame();
        spriteFrame.setTexture(texture);
        spriteFrame.setRect(rect)

        let node = new cc.Node();
        let sprite = node.addComponent(cc.Sprite);
        sprite.spriteFrame = spriteFrame;

        node.zIndex = cc.macro.MAX_ZINDEX;
        node.parent = cc.director.getScene();
        // set position
        let width = cc.winSize.width;
        let height = cc.winSize.height;
        node.x = width / 2;
        node.y = height / 2;
        node.on(cc.Node.EventType.TOUCH_START, () => {
            node.parent = null;
            node.destroy();
        });
        this.captureAction(node, width, height);
    },

5、截圖動畫(類似手機截圖,截圖後有個縮略圖動畫)

captureAction(capture, width, height) {
        let scaleAction = cc.scaleTo(1, 0.3);
        let targetPos = cc.v2(width - width / 6, height / 4);
        let moveAction = cc.moveTo(1, targetPos);
        let spawn = cc.spawn(scaleAction, moveAction);

        let finished = cc.callFunc(() => {
            capture.destroy();
        })
        let action = cc.sequence(spawn, finished);
        capture.runAction(action);
    },

6、下載圖片到本地,動態生成a標簽,模擬點擊後移除

downloadImg() {
        this.createSprite();
        var img = this.initImage();
        this.showSprite(img)
        var dataURL = this._canvas.toDataURL("image/png")
        var a = document.createElement("a")
        a.href = dataURL;
        a.download = "image";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    },

 完整代碼如下:

cc.Class({
    extends: cc.Component,

    properties: {
        _canvas: null,
        targetNode: cc.Node
    },
    onLoad() {
        this.init();
    },

    init() {
        let texture = new cc.RenderTexture();
        let gl = cc.game._renderContext;
        texture.initWithSize(this.node.width, this.node.height, gl.STENCIL_INDEX8);
        this.camera = this.node.addComponent(cc.Camera);
        this.camera.targetTexture = texture;
        this.texture = texture;
    },
    // create the img element
    initImage(img) {
        // return the type and dataUrl
        var dataURL = this._canvas.toDataURL("image/png");
        var img = document.createElement("img");
        img.src = dataURL;
        return img;
    },
    // create the canvas and context, filpY the image Data
    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;
        } else {
            this.clearCanvas();
        }
        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;
    },
    getTargetArea() {
        let targetPos = this.targetNode.convertToWorldSpaceAR(cc.v2(0, 0))
        let y = cc.winSize.height - targetPos.y - this.targetNode.height / 2;
        let x = cc.winSize.width - targetPos.x - this.targetNode.width / 2;
        return {
            x,
            y
        }
    },
    downloadImg() {
        this.createSprite();
        var img = this.initImage();
        this.showSprite(img)
        var dataURL = this._canvas.toDataURL("image/png")
        var a = document.createElement("a")
        a.href = dataURL;
        a.download = "image";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    },
    // show on the canvas
    showSprite(img) {
        let y = this.getTargetArea().y;
        let x = this.getTargetArea().x;
        let rect = new cc.Rect(x, y, 770, 800)
        let texture = new cc.Texture2D();
        texture.initWithElement(img);

        let spriteFrame = new cc.SpriteFrame();
        spriteFrame.setTexture(texture);
        spriteFrame.setRect(rect)

        let node = new cc.Node();
        let sprite = node.addComponent(cc.Sprite);
        sprite.spriteFrame = spriteFrame;

        node.zIndex = cc.macro.MAX_ZINDEX;
        node.parent = cc.director.getScene();
        // set position
        let width = cc.winSize.width;
        let height = cc.winSize.height;
        node.x = width / 2;
        node.y = height / 2;
        node.on(cc.Node.EventType.TOUCH_START, () => {
            node.parent = null;
            node.destroy();
        });
        this.captureAction(node, width, height);
    },
    // sprite action
    captureAction(capture, width, height) {
        let scaleAction = cc.scaleTo(1, 0.3);
        let targetPos = cc.v2(width - width / 6, height / 4);
        let moveAction = cc.moveTo(1, targetPos);
        let spawn = cc.spawn(scaleAction, moveAction);

        let finished = cc.callFunc(() => {
            capture.destroy();
        })
        let action = cc.sequence(spawn, finished);
        capture.runAction(action);
    },

    clearCanvas() {
        let ctx = this._canvas.getContext('2d');
        ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
    }
});

 

 

 

RenderTexture   詳細X 網路釋義 RenderTexture: 渲染紋理
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.CSS邊框 2.display屬性 3.css盒子模型 4.浮動float 5.overflow溢出屬性 :設置當元素的內容溢出其區域時發生的事情。 ​ 圓形頭像示例: ​ 總結一點: ​ width寬度設置的時候,直接可以寫100px或30%。30%這種百分比的寫法,它的寬度按照父級標簽的寬度 ...
  • //計算年齡 calcAge : function(birthday, calcDate){ var num = (calcDate.getMonth()<birthday.getMonth() || calcDate.getMonth()==birthday.getMonth() && calcD ...
  • 1. 使用 instanceof 2. 使用 isArray ...
  • 微信小程式tabBar與redirectTo 或navigateTo衝突 tabBar設置的pagePath無法再次被redirectTo或navigateTo引用 導致跳轉失敗 ...
  • "demo 代碼點此" ,篇幅有限,僅介紹幾個常用的。 start 什麼是 plugins ? While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wi ...
  • 本文轉載於: "奧怪的小棧" 這篇文章告訴你在搭建好博客後,面對網上千篇一律的美化教程怎麼才能添加自己獨特點,使人眼前一亮. [//]: (這裡開始使用markdown格式輸入你的正文.) 本站基於HEXO+Github搭建。 所以你需要準備好HEXO+Github等相關軟體和工具。詳細我會在下麵放 ...
  • formatDataToString:function (dates, formats) { var o = { "M+": dates.getMonth() + 1, //月份 "d+": dates.getDate(), //日 "H+": dates.getHours... ...
  • input::-webkit-input-placeholder{ color:red; font-size:20px; ...... } ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...