-1

I have a photograph, say flower.png, and in this photo the sixth pixel down in the third column is #23997E and I want to conditionally change that pixel's color to, say #E54864.

How is this done. I've been told that HTML canvas is how one can manipulate images pixel by pixel. How does one convert, I guess, a photograph to canvas and then be able to specify a particular pixels of that photo for styling and scripting?

tjfwalker
  • 494
  • 3
  • 18
  • 1
    There are plenty of tutorials on `canvas` on the internet that will give you detailed information on how to do what you want. – Andy Dec 01 '14 at 17:53
  • @Andy, no doubt there are many canvas tutorials, I've found general ones. Despite my searching, though, I've not found one's specifically addressing what I've described here. If you can ref any of those 'plenty' tutorials you're talking about, it'd be much appreciated. – tjfwalker Dec 01 '14 at 17:56
  • 3
    Not what SO is really for... but here's [one on pixel manipulation](http://beej.us/blog/data/html5s-canvas-2-pixel/), there's [a bunch of stuff here](http://www.html5canvastutorials.com/), and [this one will tell you how to get an image into the canvas in the first place](http://www.phpied.com/photo-canvas-tag-flip/). – Andy Dec 01 '14 at 18:00
  • I have to say, I think this question is no less appropriate (because it's no different, really) for SO than these questions: http://stackoverflow.com/questions/16228048/replace-a-specific-color-by-another-in-an-image-sprite-in-a-html5-canvas http://stackoverflow.com/questions/12992681/html-5-canvas-get-color-of-an-image-and-then-change-the-pixels-with-that-color I'm only able to find those now, after asking, because of @markE 's answer below, giving the knowledge/vocab to search for what I was needed. I first searched this considering SVG the likely solution. I'd have never figured w/o asking. – tjfwalker Dec 01 '14 at 19:22

1 Answers1

2

In its simplest form:

  1. Create a javascript Image() object: var img=new Image() ...
  2. Draw that image onto the canvas using context.drawImage(img,0,0)
  3. Set the canvas fill color as desired: context.fillStyle='#E54864'
  4. Fill pixel[3,6] with the desired color: context.fillRect(3,6,1,1)

Example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// create an Image() object
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/colorwheel1.png";
function start(){

  // draw the image onto the canvas
  ctx.drawImage(img,0,0);

  // change pixel[3,6] to  #E54864
  ctx.fillStyle='#E54864';
  ctx.fillRect(3,6,1,1);

}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<p>Pixel[3,6] is now colored #E54864</p>
<canvas id="canvas" width=300 height=300></canvas>
markE
  • 102,905
  • 11
  • 164
  • 176