View Full Version : Change Pixel Color

07-11-2012, 03:32 AM
How could I change a specific Pixel Color?

07-11-2012, 04:13 AM
Actualy How could you check a pixels color on a canvas?

07-11-2012, 04:17 AM
On a canvas I don't know, but on a webpage it's very easy. You just make a single pixel div, give it the color and position you want.

07-11-2012, 04:22 AM
Hmm thanks but currently I need to figure out canvas..

07-11-2012, 02:05 PM
Actualy How could you check a pixels color on a canvas?
This is only for Checking, Do you still want help with changing?

First you'll have to get the ImageData of the specific pixel of your canvas:

var xPixel
var yPixel

var pixelData canvasContext.getImageData(xPixel - 1, yPixel - 1, 1, 1).data;

The pixelData variable wil now contain a array with your rgb and transperancy values:

var red = pixelData[0];
var green = pixelData[1];
var blue = pixelData[2];
var transperancy = pixelData[3]/255;(this is a value from 0 - 255 so I convert it to 0 - 1)

07-11-2012, 02:24 PM
For changing you'll need the imageData:

var xPixel;
var yPixel;
var imageData = canvasContext.getImageData(xPixel - 1, yPixel -1, 1, 1);

Then you need to change the rgba values:

var red; //value between 0 and 255
var green; //value between 0 and 255
var blue; //value between 0 and 255
var transparency; //value between 0 and 1

imageData.data[0] = red;
imageData.data[1] = green;
imageData.data[2] = blue;
imageData.data[3] = transparency * 255;

And finally we need to place the imageData back into the canvas:

canvasContext.putImageData(imageData, xPixel - 1, yPixel - 1);

Note if you want to change a bunch of pixel it might be easier to get a bigger part of the imageData

07-11-2012, 05:01 PM
I can set them like this

var x =1;
var y =1;
var c=document.getElementById("mapa");
var ctx=c.getContext("2d");

07-11-2012, 06:46 PM
I guess that would make more sense, I was kinda in the ImageData mood for some reason