javascript - 什么是使用 getImageData、javascript、HTML5 canvas 导致内存泄漏

标签 javascript memory-leaks canvas getimagedata

我正在使用“ Canvas ”元素,并尝试在 FIrefox 4 中使用 Javascript 对图像进行一些基于像素的操作。

以下代码泄漏了内存,我想知道是否有人可以帮助确定泄漏的原因。

使用的图像是预加载的,一旦加载(到 pImages 数组中)就会调用此代码片段。

    var canvas = document.getElementById('displaycanvas');
    if (canvas.getContext){
        var canvasContext = canvas.getContext("2d");
        var canvasWidth = parseInt(canvas.getAttribute("width"));
        var canvasHeight = parseInt(canvas.getAttribute("height"));

        // fill the canvas context with white (only at start)
        canvasContext.fillStyle = "rgb(255,255,255)";
        canvasContext.fillRect(0, 0, canvasWidth, canvasHeight);

        // for image choice
        var photoIndex;

        // all images are the same width and height
        var imgWidth    = pImages[0].width;
        var imgHeight   = pImages[0].height;

        // destination coords 
        var destX, destY;

        // prep some canvases and contexts
        var imageMatrixCanvas               = document.createElement("canvas");
        var imageMatrixCanvasContext        = imageMatrixCanvas.getContext("2d");


        // Set the temp canvases to same size - apparently this needs to happen according 
        // to one comment in an example - possibly to initialise the canvas?
        imageMatrixCanvas.width         = imgWidth;
        imageMatrixCanvas.height        = imgHeight;

        setInterval(function() { 
            // pick an image
            photoIndex = Math.floor(Math.random() * 5);

            // fill contexts with random image
            imageMatrixCanvasContext.drawImage(pImages[photoIndex],0,0);
            imageMatrixData = imageMatrixCanvasContext.getImageData(0,0, imgWidth, imgHeight);

            // do some pixel manipulation
            // ...
            // ...

            // choose random destination coords (inside canvas)
            destX = Math.floor(Math.random() * (canvasWidth - imgWidth));
            destY = Math.floor(Math.random() * (canvasHeight - imgHeight));

            // show the work on the image at the random coords
            canvasContext.putImageData(imageMatrixData, destX, destY);
        }, 500);        
    }

最佳答案

哦..错误。经过几次测试,内存看起来还不错。
但是还有一个问题。
更改 img 元素的 src 属性时,选项卡进程使用的内存大小正在增长...

Src property = canvas.getContext('2d').toDataURL('image/png') (changing each time);

我试过“删除 img.src”,删除节点...

关于javascript - 什么是使用 getImageData、javascript、HTML5 canvas 导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4892265/

相关文章:

C# WebAPI 垃圾回收

java - XPages:有人可以解释一下这些消息吗?

javascript - 如何选择在canvas2d中制作字形纹理的字体大小

javascript - Canvas : shape + shadow

javascript - 为什么当我在另一个函数完成后调用函数时,它会调用所有之前的函数?

javascript - 移动图像不能超出窗口 DOM

javascript - 如何引用div标签的Javascript函数来添加逗号?

c - 如何重新分配一些使用 calloc 分配的内存?

JavaFX 在 fxml 中调整 Canvas 大小

javascript - KnockoutJS 与 jQuery Datatables 和绑定(bind)插件,行单击传递整个数组而不是单个模型