Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

blend two images on a javascript canvas

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

like image 296
davivid Avatar asked Sep 05 '10 23:09

davivid


People also ask

Does JavaScript work in canvas?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.


1 Answers

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>
like image 167
pepkin88 Avatar answered Sep 19 '22 15:09

pepkin88