欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

cocos creator 小游戏区域截图功能实现

程序员文章站 2022-03-23 13:45:07
截图是游戏中非常常见的一个功能,在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: 渲染纹理