Git Product home page Git Product logo

canvasfilter's Introduction

Build Status

canvasfilter.js

Mainly this library extends the canvas context object (CanvasRenderingContext2D) with image processing filters. It aims to make it easy and strait forward to use.

Inspired by - Based on

https://github.com/kig/canvasfilters

http://www.html5rocks.com/en/tutorials/canvas/imagefilters/

Big thanks for that.

Current State

A lot of filters should be working fine. A couple are missing, though. Like Sobel filter. Due to the Float32 problematic.

Note that ImageData values are clamped between 0 and 255, so we need to use a Float32Array for the gradient values because they range between -255 and 255.

Browser support

For the main part it should be working in browsers supporting canvas.

http://caniuse.com/#search=canvas

Personally I tested it on FireFox (31) and Chrome (37 ~ beta).

Planed in near future

  • Setting up test environment. (e.g. travis-ci, browser testing etc.)
    • complete all test cases (/test/*.test.js)
  • Create examples and demo page.
  • Of course bug fixing, improvements and extending.
  • Maybe make it ready for nodejs environment.

Getting Started

Just download and use it. Or you can use bower.

bower install fentas/canvasfilter

Last step is to insert it into your website/app.

<script src="path/to/canvasfilter/canvasfilter.js"></script>

Usage

As said before the library tries to make it simple as possible. For starters one example.

<img src="/picture.jpg">
<script>
// turns into canvas object
var ctx = document.querySelector('img').toCanvas().getContext('2d');
// applies grayscale filter and flips the image vertically
ctx.filter.grayscale().flipVertical();
// and for convenience turn it into an image again
ctx.canvas.toImage();
</script>

CanvasFilter methods

All the filters are found within filter attribute (in CanvasRenderingContext2D object)

var ctx = canvas.getContext('2d');
ctx.filter // << here is the image processing collection. ~ CanvasFilter
Image processing filters.
  • CanvasFilter *.flipHorizontal()

Flips the image horizontally.

  • CanvasFilter *.flipVertical()

Flips the image vertically.

  • CanvasFilter *.luminance()
  • CanvasFilter *.grayscale()
  • CanvasFilter *.grayscaleAvg()
  • CanvasFilter *.threshold(threshold, high, low)
  • CanvasFilter *.invert()
  • CanvasFilter *.erode()
  • CanvasFilter *.distortSine()

Not working right now. (Performance issue?)

Convolution. ?
  • CanvasFilter *.convolve(weightsVector, opaque)
  • CanvasFilter *.convolveVertical(weightsVector, opaque)
  • CanvasFilter *.convolveHorizontal(weightsVector, opaque)
  • CanvasFilter *.laplace()

This method simply applies the following matrix.

[-1,-1,-1,
 -1, 8,-1,
 -1,-1,-1]
  • CanvasFilter *.gaussianBlur()
Blending methods.

This enables you to blend two images together. First call *.blend(object[, scaling[, above]]).

object

Any image object like

  • HTMLImageElement
  • HTMLCanvasElement
  • CanvasRenderingContext2D
  • CanvasFilter

scaling default: center

The method how the object image will overlay the given image.

  • center
  • stretch
  • fit not implemented yet

above default: false

Whether the given image should be above or below of the other image.

Next there are several methods available how to blend both images together.

  • CanvasFilter *.blend([...]).darken()
  • CanvasFilter *.blend([...]).lighten()
  • CanvasFilter *.blend([...]).multiply()
  • CanvasFilter *.blend([...]).screen()
  • CanvasFilter *.blend([...]).add()
  • CanvasFilter *.blend([...]).sub()
  • CanvasFilter *.blend([...]).difference()

One example for this:

var ctx = canvas.getContext('2d');
ctx.filter.blend(document.querySelector('img')).sub();
Look Up Table (LUT). ?

This gives the functionality to use LUTs. For this there exists a separate object - LookUpTable. In order to work with this following method is given.

  • LookUpTable *.lookUpTable()

The LookUpTable object consists of predefined methods and 4 different matrices. Each for every color plus one for alpha (r,g,b and a).

The predefined methods will set all matrices to perform as described:

  • LookUpTable [LookUpTable].invert()
  • LookUpTable [LookUpTable].brightnessContrast(brightness, contrast)
  • CanvasRenderingContext2D [LookUpTable].apply()

This method will apply all matrices to the given image and return the canvas context (CanvasRenderingContext2D).

Now there is also the possibility to set each matrix itself. Each matrix can be access simply like this ColorMap [LookUpTable].a for example. This will return a ColorMap object which is basically a array/vector (of 255 values). You can set each value as you like (e.g. [LookUpTable].a[42] = 13;) or use the following methods:

  • LookUpTable [ColorMap].identity() is default
  • LookUpTable [ColorMap].invert()
  • LookUpTable [ColorMap].brightnessContrast(brightness, contrast)

At last another example, inverting the green spectrum and applying the result:

var ctx = canvas.getContext('2d'),
    lut = ctx.filter.lookUpTable();

lut.g.invert().apply()
//btw. you could resume the chain like: *.filter.flipVertical()

The rest

  • ImageData *.getPixels()

Returns simply the complete image data of the canvas object.

  • *.getBilinearSample(x, y, px)

More info: http://en.wikipedia.org/wiki/Bilinear_filtering

Other useful extensions

There are some extension to some of the HTML dom objects to make the workflow more convenient.

HTMLImageElement

  • HTMLCanvasElement *.toCanvas([keep, [complete]])
  • HTMLCanvasElement *.toCanvas([complete])

Converts img to canvas with the image data.

keep default: false

If true img tag will not be replace instead it just returns the canvas tag/object.

complete default: funcion() {}

Use this if you are not sure if the given image is not completely loaded. If the image is not loaded this method will return null because there is nothing to replace. The scope of the function will point to the created canvas object (this instanceof HTMLCanvasElement).

document.querySelector('img').toCanvas(function() {
  // makes sure image is completely loaded
  this.filter.grayscale();
}

HTMLCanvasElement

  • HTMLImageElement *.toImage([keep, [type, [args]]])

Converts canvas to image with canvas image data. Basically it uses canvas image data url.

keep default: false

If true canvas tag will not be replaced instead it just returns the img tag/object

type default: image/png

More info: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement#toDataURL

  • HTMLCanvasElement *.cloneNode([deepClone, [context]])

This extends the given cloneNode.

deepClone default: false

If true it clones also the old image data instead of cloning only the canvas element.

context default: '2d'

What kind of context should be cloned. At the moment only '2d' is supported.

CanvasRenderingContext2D

  • CanvasRenderingContext2D *.clone()

Clones the given canvas context. E.g. nice to have for blending methods.

var ctx = document.querySelector('img').toCanvas().getContext('2d');
// applies grayscale filter and flips the image vertically
canvas.filter.blend(ctx.clone().filter.grayscale().flipVertical()).darken();
  • CanvasRenderingContext2D *.restore()

Restores the image data to its original data.

Side notes

If you plan to tinker around with images stored somewhere other then your server be aware that this could resolve into following error:

SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

If you have access to this particular server you could solve this like this.

Donations

Please help me to finance my every cup of tea. Every coin is appreciated.

Sick of tea? That’s like being sick of *breathing*! - Uncle Iroh

197EypPopXtDPFK6rEbCw6XDEaxjTKP58S -- bitcoin ?

-- paypal

Or just flattr me.

canvasfilter's People

Contributors

fentas avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.