views:

50

answers:

1

How do you blend two arrays of pixel data to create one image? with the option of using different blending modes?

+2  A: 

Pixastic is a special framework for advanced use of canvas, here are blending examples: http://www.pixastic.com/lib/docs/actions/blend/

If you would like do this alone, you can extract pixel data from 2 images, blend it with a mathematical equation, and put into a canvas. Here is information how to get and put pixel data from/to canvas: http://ajaxian.com/archives/canvas-image-data-optimization-tip


Update: Simple example with alpha blending of 2 images in proportion 50-50. (Images borrowed from http://www.pixastic.com/sample/Butterfly.jpg and http://www.pixastic.com/sample/Flower.jpg )

<img src="Butterfly.jpg" id="img1">
<img src="Flower.jpg" id="img2">
<p>Blended image<br><canvas id="canvas"></canvas></p>
<script>
window.onload = function () {
    var img1 = document.getElementById('img1');
    var img2 = document.getElementById('img2');
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var width = img1.width;
    var height = img1.height;
    canvas.width = width;
    canvas.height = height;

    var pixels = 4 * width * height;
    context.drawImage(img1, 0, 0);
    var image1 = context.getImageData(0, 0, width, height);
    var imageData1 = image1.data;
    context.drawImage(img2, 0, 0);
    var image2 = context.getImageData(0, 0, width, height);
    var imageData2 = image2.data;
    while (pixels--) {
        imageData1[pixels] = imageData1[pixels] * 0.5 + imageData2[pixels] * 0.5;
    }
    image1.data = imageData1;
    context.putImageData(image1, 0, 0);
};
</script>
pepkin88
thanks, you made me realise I just needed to google 'blending equations' or such like to find the right formulas as well.
davivid
Thats a good optimization technique I hadn't been using! and a pretty useful library by the look of it - although Id prefer to learn how to do these things myself first.
davivid