HTML5 Canvas Clear

Posted at


function canvas_clear(canvas){ //clear canvas' path and content, reset tranform. return reference to same object.
var context = canvas.getContext("2d");
context.beginPath();
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
//canvas.width = canvas.width; //don't use!
return canvas;
};

function canvas_clear_deep(canvas){ //clear canvas' path and content, reset tranform (as before).
var tmp = canvas.cloneNode(true); // + NEW: unhook event-handlers (optional: attribute-events too)
// + update DOM with fresh-canvas.
// + clear unused memory.
// + return reference to fresh-canvas.

/* //optionally enable this part to also remove inline(attribute)-events.
  NamedNodeMap.prototype.forEach = Array.prototype.forEach; //optionally unhook inline(""attribute"")-event
  tmp.attributes.forEach(function(attribute){
                           if(false === /^on/i.test(attribute.nodeName)) return;
                           tmp.removeAttribute(attribute.nodeName);
                         });
  */

tmp = canvas_clear(tmp);
if(null !== canvas.parentElement){ //replace with fresh-canvas
canvas.parentElement.replaceChild(tmp, canvas);
}

//cleanup
canvas = canvas_clear(canvas);
canvas = undefined;

return tmp;
};

HTMLCanvasElement.prototype.clear = function(){ return canvas_clear(this); };
HTMLCanvasElement.prototype.clear_deep = function(){ return canvas_clear_deep(this); };

Also available on this gist: https://gist.github.com/eladkarako/a005225594ade65347e2f5ad4c55d131

And just use canvas.clear() or canvas.clear_deep() :]

Enjoy!