From 9e6fd5a7e74393bac6186fb61d2feca22c995cf8 Mon Sep 17 00:00:00 2001 From: Jonathan Puckey Date: Sat, 26 Feb 2011 15:29:51 +0100 Subject: [PATCH] Speed up CanvasProvider. --- src/util/CanvasProvider.js | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/util/CanvasProvider.js b/src/util/CanvasProvider.js index d7fa9793..0622bfbd 100644 --- a/src/util/CanvasProvider.js +++ b/src/util/CanvasProvider.js @@ -1,17 +1,32 @@ +// TODO: it might be better to make a ContextProvider class, since you +// can always find the canvas through context.canvas. This saves code and +// speed by not having to do canvas.getContext('2d') +// TODO: Run through the canvas array to find a canvas with the requested +// width / height, so we don't need to resize it? CanvasProvider = { canvases: [], getCanvas: function(size) { - var canvas = this.canvases.length - ? this.canvases.pop() - : document.createElement('canvas'); - canvas.width = size.width; - canvas.height = size.height; - return canvas; + if(this.canvases.length) { + var canvas = this.canvases.pop(); + // If they are not the same size, we don't need to clear them + // using clearRect and visa versa. + if((canvas.width != size.width) || (canvas.height != size.height)) { + canvas.width = size.width; + canvas.height = size.height; + } else { + var context = canvas.getContext('2d'); + context.clearRect(0, 0, size.width + 1, size.height + 1); + } + return canvas; + } else { + var canvas = document.createElement('canvas'); + canvas.width = size.width; + canvas.height = size.height; + return canvas; + } }, returnCanvas: function(canvas) { - // reset canvas: - canvas.width = canvas.width; this.canvases.push(canvas); } -}; +}; \ No newline at end of file