日期:2014-05-17  浏览次数:20845 次

HTML5(三)color pixel and picture
HTML5(三)color pixel and picture

1.color
every pixel (picture element) are consist of 4 bytes.
first byte decide the red value
second byte decide the green value
third byte decide the blue value
fourth byte decide the transparency value

the value range is 0~255

(255,0,0,255) stand for pure red, in memory it is 11111111 00000000 000000000 11111111

2. manage pixel
Object ImageData stores the pixel value, it contains width,height and data properties. data property is a array.
imageData.data[index*4 + 0]
imageData.data[index*4 + 1]
imageData.data[index*4 + 2]
imageData.data[index*4 + 3]

They stands for the index+1 pixel red value, green value and blue value and transparency value.

The picture is width * height pixels. So we have width * height * 4 values in data array.

There are 3 method in context:
createImageData(width,height)     all the pixels are rgba(0,0,0,0)
getImageData(x,y,width,height)
putImageData(data,x,y)

3. simple sample
my file is test3.html, we must put in under apache and test it.

<canvas id="test1" width="280" height="200" style="background-image:url(banner1.gif)">
you are out!
</canvas>

<br />
red value:<input type="range" min="1" max="100" onchange="colorChange(event,0)"/>
<br />
green value:<input type="range" min="1" max="100" onchange="colorChange(event,1)"/>
<br />
blue value:<input type="range" min="1" max="100" onchange="colorChange(event,2)"/>
<br />
transparency:<input type="range" min="1" max="100" onchange="colorChange(event,3)"/>

<script type="text/javascript">

    //get the context

    var canvas = document.getElementById("test1");

    var ctx = canvas.getContext("2d");

    //get width and height of canvas
    var width = parseInt(canvas.getAttribute("width"));
    var height = parseInt(canvas.getAttribute("height"));

    //load the image
    var image = new Image();
    image.onload =imageLoaded;
    image.src = "banner2.gif";
    //save the array of image data
    var imageData=null;
    function imageLoaded() {
        // draw the image on canvas
        ctx.drawImage(image, 0, 0);
        imageData = ctx.getImageData(0, 0, width, height);
    }

    function colorChange(event,offset){
        imageLoaded();
        for (var y = 0; y < imageData.height; y++) {
            for (x = 0;x < imageData.width; x++) {
                //index = pixel number
                var index = y * imageData.width + x;
                var p = index * 4;
                var color = imageData.data[p + offset] * event.target.value / 50;
                // color value range is [0..255]