P
P
Pavel Shvedov2014-06-08 22:08:25
JavaScript
Pavel Shvedov, 2014-06-08 22:08:25

How to speed up image processing in HTML5 Canvas

Good day, I practice with CoffeeScript and HTML5 Canvas, I found a simple blur algorithm on the Internet, I implemented it in CoffeeScript, but it works very slowly, in reality, a 500 by 500 pixel image is processed for 5 seconds, at which time the browser dies (Safari, Chrome OSX 10.9). Any ideas to speed up this process? Thoughts on how to speed up the pixel-by-pixel traversal of the image do not yet come to my mind. Here is the blur implementation code in CoffeeScript:

class BlurEffect extends BasicEffect
  constructor: (@_radius, @_ctx) ->

  proceed: (target) ->
    newImageData = @_ctx.createImageData(target)
    w = target.width
    h = target.height
    for i in [0...w]
      for j in [0...h]
        total = {
          red: 0
          green: 0
          blue: 0
        }
        for ky in [[email protected][email protected]_radius]
          for kx in [[email protected][email protected]_radius]
            pixel = @getPixel(target, i+kx, j+ky)
            total.red+=pixel.red
            total.green+=pixel.green
            total.blue+=pixel.blue
        newImageData.data[(j * w * 4) + (i * 4)] = total.red/ Math.pow(@_radius * 2 + 1, 2)
        newImageData.data[(j * w * 4) + (i * 4) + 1] = total.green/ Math.pow(@_radius * 2 + 1, 2)
        newImageData.data[(j * w * 4) + (i * 4) + 2] = total.blue/ Math.pow(@_radius * 2 + 1, 2)
        newImageData.data[(j * w * 4) + (i * 4) + 3] = target.data[(j * w * 4) + (i * 4) + 3]
    newImageData

The code seems to be primitive, needs no explanation.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
0
0re1, 2014-06-08
@mmmaaak

- no need to calculate Math.pow(@_radius * 2 + 1, 2) every time
- don't call @getPixel every time, but pull ImageData into a Typed Array
- don't use the total object, but store named variables red, green, blue
- count (j * w * 4) + (i * 4) once instead of five times
- don't use CoffeeScript, for ky in [[email protected][email protected]_radius]it will overhead the direction definitions
- asm-js can come in handy here
I think it would be faster to use CSS .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question