开发者

How to make webkit free canvas context memory when canvas is destroyed

开发者 https://www.devze.com 2023-02-08 02:12 出处:网络
T开发者_Python百科he code below seems to leak memory at a rather alarming rate on webkit (mobile safari & konqueror). I realize the test case could be rewritten to reuse the canvas instead of crea

T开发者_Python百科he code below seems to leak memory at a rather alarming rate on webkit (mobile safari & konqueror). I realize the test case could be rewritten to reuse the canvas instead of creating a new one, but I'm wondering why the below doesn't also work. Any insight would be appreciated.

<html>
<head>
<script>
function draw() { 
    var holder = document.getElementById("holder");
    holder.innerHTML = "<canvas id=cnv height=250 width=250>"; 
    var ctx = document.getElementById("cnv").getContext("2d");
    ctx.beginPath();
    ctx.moveTo(50,50);
    ctx.lineTo(Math.random()*100,Math.random()*100);
    ctx.stroke();
}

function start() {
    setInterval(draw, 100);
}
</script>
</head>
<body onload="start()">
<div id="holder"></div>
</body>
</html>


This issue happens on Webkit even when an image SRC is modified, so I don't get surprised if this happens when handling canvas too.

There is a bug filled on Chrome (that made them filling a bug to Webkit) and we hope this will be fixed soon, as it is making many Chrome extension unusable.

references http://code.google.com/p/chromium/issues/detail?id=36142 https://bugs.webkit.org/show_bug.cgi?id=23372

Anyway, the suggestions above should mitigate this.


Don't:

  • Create the <canvas> element with .innerHTML
  • Create the <canvas> in each Interval

Do:

  • use var cv = document.createElement('canvas'); cv.setAttribute('height', '250'); // ...
  • cache the reference of cv at some init point and re-use that!!

    <script>
            var holder = document.getElementById("holder"),
            var cv = document.createElement('canvas');
                cv.setAttribute('id', 'cnv');
                cv.setAttribute('height', '250');
                cv.setAttribute('width', '250');
                holder.appendChild(cv);

            function draw() {                     
                var ctx = cv.getContext("2d");
                ctx.beginPath();
                ctx.moveTo(50,50);
                ctx.lineTo(Math.random()*100,Math.random()*100);
                ctx.stroke();
            }

            function start() {
                setInterval(draw, 100);
            }
    </script>
0

精彩评论

暂无评论...
验证码 换一张
取 消