Skip to content

Instantly share code, notes, and snippets.

@markbiek
Created January 16, 2012 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markbiek/1621650 to your computer and use it in GitHub Desktop.
Save markbiek/1621650 to your computer and use it in GitHub Desktop.
An improved setPixel function for drawing on a canvas (allows color to be specified using HTML hex codes)
Object.prototype.setPixel = function(point, rgba) {
if(!this.hasOwnProperty('data')) {
throw'This method only works with ImageData objects created with createImageData';
}
var imageData = this;
if(typeof rgba == 'string') {
var useDefault = true; //If anything is wrong with the hex code, fall back to a default color
var matches;
//We were passed a string so let's see if it's a valid hex code
if(rgba.length == 7) {
//Full length hex code (eg #AABBCC)
matches = rgba.toLowerCase().match(/#([abcdef0-9]{2})([abcdef0-9]{2})([abcdef0-9]{2})/);
}else if(rgba.length == 4) {
//Short hex code (eg #ABC)
matches = [
'',
rgba[1]+rgba[1],
rgba[2]+rgba[2],
rgba[3]+rgba[3]
];
}
if(matches.length == 4) {
rgba = [];
for(var i=1;i<=3;i++) {
rgba.push(parseInt(matches[i],16));
}
rgba.push(255); //Add the alpha
useDefault = false;
}
if(useDefault) {
rgba = [255,255,255,255];
}
}
if(rgba.length <= 3 ) { rgba.push(255); } //Add alpha if not provided
i = (point.x + point.y * imageData.width) * 4;
console.log('Drawing at ' + point.x + ',' + point.y);
imageData.data[i ] = rgba[0]; //r
imageData.data[i+1] = rgba[1]; //g
imageData.data[i+2] = rgba[2]; //b
imageData.data[i+3] = rgba[3]; //a
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment