[Bug] Memory Issue with Context 2D

Plugins used : None.

Explanation :
As the title states, I've found an issue regarding memory with the canvas.getContext('2d') object, it seems that when you call context before assigning it to a texture( and uploading it to the gpu ), the memory usage( ram, not gpu ), is increased, on top of this the ram don't seem to clear when the texture is destroyed, as it should. This is very easy to replicate, however it may not be as simple to fix, since all bitmaps make an immediate call to store the canvas context, which means that this issue happens for every bitmap created.

Error report : No error report, just watch your computers ram usage.

How to replicate : Run the below code in your console from both examples, one after the other while you have task manager open and on the performance tab, make sure memory is selected.

Example 1
Code:
//------------------------------------------------------------------------------
// no reference to context :
//------------------------------------------------------------------------------

// run this code to create a new sprite with a base texture from a canvas.

canvas = document.createElement( 'canvas' );
canvas.width = 10000, canvas.height = 10000;
sprite = new Sprite();
sprite.texture.baseTexture = new PIXI.BaseTexture( canvas );
Graphics._renderer.bindTexture( sprite.texture );

// after you run the above code, run this to destroy the texture,
// you'll see the ram free up immediately.
sprite.texture.destroy( true );

Example 2
Code:
//------------------------------------------------------------------------------
// context referenced :
//------------------------------------------------------------------------------

// run this code and you'll see something nearly identical,
// except the amount of ram consumed is much larger.
canvas = document.createElement( 'canvas' );
canvas.width = 10000, canvas.height = 10000;
canvas.getContext( '2d' );
sprite = new Sprite();
sprite.texture.baseTexture = new PIXI.BaseTexture( canvas );
Graphics._renderer.bindTexture( sprite.texture );


// after you run the above code, run this to destroy the texture,
// you'll see the ram does not get freed.
sprite.texture.destroy( true );

Sample Project:
Dropbox

In the demo, I've simply made two boxes( not the most elegant, I know ).

Clicking box A will create a large texture and upload it to gpu( no getContext2D call ), clicking the box again, will free the memory and delete the texture.

Clicking box B will create a large texture( this time with a call to getContext2D ), clicking the button again will free the memory and delete the texture( or at least it should, but it does not ).
plz add
PHP:
var debugWin = require('nw.gui').Window.get();
debugWin.showDevTools();
and also console log for look and debug your demo
If am understand.
sprite.texture.destroy work for pixi only.
if you take a look
PHP:
Texture.prototype.destroy = function destroy(destroyBase) {
        if (this.baseTexture) {
            if (destroyBase) {
                // delete the texture if it exists in the texture cache..
                // this only needs to be removed if the base texture is actually destroyed too..
                if (_utils.TextureCache[this.baseTexture.imageUrl]) {
                    Texture.removeFromCache(this.baseTexture.imageUrl);
                }

                this.baseTexture.destroy();
            }

            this.baseTexture.off('update', this.onBaseTextureUpdated, this);
            this.baseTexture.off('loaded', this.onBaseTextureLoaded, this);

            this.baseTexture = null;
        }

        this._frame = null;
        this._uvs = null;
        this.trim = null;
        this.orig = null;

        this.valid = false;

        Texture.removeFromCache(this);
        this.textureCacheIds = null;
    };
so i think it because canvas are not registered to you textures cache from pixi utility tool.
S oif you use canvas from document create , you will need to rewrite the proto
Apologies maybe I was a bit unclear, theres nothing for you to view in the console, at least not in the demo, the demo does everything by clicking the buttons.

Also you are correct, the destroy function does only destroy the texture, but that's where the issue is happening. Try pressing ctrl+shift+esc ( if you're on windows ), to open your task manager, click the performance tab, and make sure memory is highlighted. then try clicking the buttons in the demo( click the first one, then click it again to free memory, then try the second button and keep an eye on your ram usage ). perhaps it's just on my end(?), but this was my results.
Spoiler
Untitled.thumb.png.84c8a5a65792dcbf489e952cd92823f5.png

The large spikes in memory are where the bitmaps were loaded, the only difference is the memory doesn't decrease on the bottom example, while it does on the top.

Edit : also keep in mind the bottom one is how bitmaps work in MV, you can easily get the same results by creating a bitmap with the same dimensions and adding it to a sprite, then adding it to your scene.
upload_2018-3-19_1-10-41.png
use the memory task manager from window i not really good way, for me i have too much software run in background that can make fals result.
Example my nvidia software will increase when i play game .
Again, this is not something visible through the console, try running this with task manager open( see screenshot in my previous post ^^ ).
sorry but its work for me !
i don't know what to tell you !
so when i do mass click on A .
Huge memory load , and all fired correctly.
Mass click on B just do nothing to memory. (not increase)
index.php
you can also try this in your package.json

PHP:
"chromium-args" : "--show-fps-counter"
or
PHP:
"chromium-args" : "--force-gpu-mem-available-mb=10000 --show-fps-counter --enable-gpu-rasterization --enable-gpu-memory-buffer-video-frames --enable-native-gpu-memory-buffers ",
and look if your gpu memory fired.
Hmmm that's odd, maybe it's just an issue with my pc, however I'm quite certain everything is up to date and running properly. I'm curious if this happens for anyone else as well, or maybe it's just me. I just know this is how MV's always acted for me which i thought was strange that everytime I play a game made in MV my rams always through the roof, so I decided to look into the issue, and this was what i'd found. 🙂 Also thanks for giving this a test as well.
but is necessary for you to use canvas 2D ?
pixi.graphic does everything better no?

you can maybe take a look how pixi register canvas 2d
But i don't know how this work.In my side i was use canvas 2d in a very old plugin for create graphic, but was not the good way.
PHP:
    BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) {
        var svgSize = (0, _utils.getSvgSize)(svgString);

        var svgWidth = svgSize.width;
        var svgHeight = svgSize.height;

        if (!svgWidth || !svgHeight) {
            throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.');
        }

        // Scale realWidth and realHeight
        this.realWidth = Math.round(svgWidth * this.sourceScale);
        this.realHeight = Math.round(svgHeight * this.sourceScale);

        this._updateDimensions();

        // Create a canvas element
        var canvas = document.createElement('canvas');

        canvas.width = this.realWidth;
        canvas.height = this.realHeight;
        canvas._pixiId = 'canvas_' + (0, _utils.uid)();

        // Draw the Svg to the canvas
        canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight);

        // Replace the original source image with the canvas
        this.origSource = this.source;
        this.source = canvas;

        // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`)
        BaseTexture.addToCache(this, canvas._pixiId);

        this.isLoading = false;
        this._sourceLoaded();
        this.emit('loaded', this);
    };
Yeah I'm aware of how pixi can work without DOM Canvas objects, however I was looking into this issue because rpg maker MV's bitmap class uses canvas objects, then it creates a pixi texture( just like I did in the examples i posted ).

Taken from rpg_core.js.

Code:
Bitmap.prototype._createCanvas = function(width, height){
    this.__canvas = this.__canvas || document.createElement('canvas');
    this.__context = this.__canvas.getContext('2d');

    this.__canvas.width = Math.max(width || 0, 1);
    this.__canvas.height = Math.max(height || 0, 1);

    if(this._image){
        var w = Math.max(this._image.width || 0, 1);
        var h = Math.max(this._image.height || 0, 1);
        this.__canvas.width = w;
        this.__canvas.height = h;
        this._createBaseTexture(this._canvas);

        this.__context.drawImage(this._image, 0, 0);
    }

    this._setDirty();
};

Edit : ahh sorry, I'm a bit tired lol, i think i misread that bit, but yeah I looked into how pixi loads canvas based textures, but unfortunately I came up short 🙁 I only know that after the image gets uploaded to the gpu, after that it starts making calls to a few different libraries outside of the pixi.js plugin itself. Thanks for pointing me to that bit of code though, the effort is much appreciated. ^_^
what am just see, you maybe need to add to register like this.
PHP:
 BaseTexture.addToCache(this, canvas._pixiId);
but I may be wrong, but it seems logical for your context.
The textures iirc should already be cached, since the memory is clearing in the first example, unless somehow calling context2D is uncache-ing the texture, but I don't think that's the issue. If that was the issue as well, you'd have the problem on your end as well, I believe it could just hardware related at this point.

Few other things I tried were clearing the canvas object itself( setting it's width, height to 0, and setting it to null ), as well as setting the context object to null( since the context holds reference of the canvas ), on top of destroying the texture, the sprite, and forcing garbage collection after doing all that, but it just still don't seem to clear up the ram :|

Anyways, thanks for the assistance @Jonforum, I'm just going to stick with using textures without canvas objects for my plugins, lol it's less headache, and I don't have this issue with them. 😀

Edit : " browser can remember RGBA state of canvas /image and then drop it, no guarantees about when it actually drops it.", recieved this info from ivan.popelyshev
at html5 game devs forums, although I'm still unsure why just making a call to the context2D before uploading the texture is causing nwjs to retain the data longer( at least for me ).

Also after further testing, it seems the ram does clear itself, if i leave my computer idle for about 5 minutes or so( not fully, but I'm sure if i leave it longer, it'll fully clear itself eventuallly ), so I think this topic can be closed, as it's not actually a bug, it's just the way chrome handles canvas objects.
Thread closed IgnoreMe

Original thread: https://forums.rpgmakerweb.com/threads/bug-memory-issue-with-context-2d.92872/