From 376fda7361e76da3cf56ad5aa5dd7caee8efa887 Mon Sep 17 00:00:00 2001 From: Isaiah Odhner Date: Wed, 17 Jan 2018 22:18:52 -0500 Subject: [PATCH] Optimize unnecessarily and simplify returning an Array --- src/helpers.js | 36 +++++++++++++++++------------------- src/image-manipulation.js | 9 +++++++++ 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/src/helpers.js b/src/helpers.js index ababa6d..fd9cca5 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -41,25 +41,23 @@ function E(t){ return document.createElement(t); } -// TODO optimization: could keep one canvas for this purpose -function get_rgba_from_color(color){ - - var _c = new Canvas(1, 1); - - _c.ctx.fillStyle = color; - _c.ctx.fillRect(0, 0, 1, 1); - - var _id = _c.ctx.getImageData(0, 0, 1, 1); - - // We could just return _id.data, but let's return an array instead - // Could also do Array.from(_id.data) - var fill_r = _id.data[0]; - var fill_g = _id.data[1]; - var fill_b = _id.data[2]; - var fill_a = _id.data[3]; - return [fill_r, fill_g, fill_b, fill_a]; - -} +var get_rgba_from_color = (function(){ + var _single_pixel_canvas = new Canvas(1, 1); + + function get_rgba_from_color(color){ + + _single_pixel_canvas.ctx.fillStyle = color; + _single_pixel_canvas.ctx.fillRect(0, 0, 1, 1); + + var _id = _single_pixel_canvas.ctx.getImageData(0, 0, 1, 1); + + // We could just return _id.data, but let's return an Array instead + // I'm not totally sure _id.data wouldn't keep _id around in memory + return Array.from(_id.data); + } + + return get_rgba_from_color; +}()); function Canvas(width, height){ var image = width; diff --git a/src/image-manipulation.js b/src/image-manipulation.js index 7a6a53c..8bf42cc 100644 --- a/src/image-manipulation.js +++ b/src/image-manipulation.js @@ -211,6 +211,15 @@ function brosandham_line(x1, y1, x2, y2, callback){ function draw_fill(ctx, x, y, fill_r, fill_g, fill_b, fill_a){ + // TODO: split up processing in case it takes too long? + // progress bar and abort button (outside of image-manipulation.js) + // or at least just free up the main thread every once in a while + // TODO: speed up with typed arrays? https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipulation-with-typed-arrays/ + // could avoid endianness issues if only copying colors + // the jsperf only shows ~15% improvement + // maybe do something fancier like special-casing large chunks of single-color image + // (octree? or just have a higher level stack of chunks to fill and check at if a chunk is homogeneous) + var stack = [[x, y]]; var c_width = canvas.width; var c_height = canvas.height;