title: Canvas - Change colors of an image using HTML5/CSS/JS?
body: <p>Is there a way to change colors of an image much like in Flash/ActionScript with using only HTML5/CSS/JavaScript?</p>
  
  <p>Here's an example in Flash: <a href="http://www.kirupa.com/developer/actionscript/color.htm" rel="noreferrer">http://www.kirupa.com/developer/actionscript/color.htm</a> <strong>EDIT: This is the process I wish to duplicate.</strong></p>
  
  <p>I'm trying to accomplish something like this (color changing aspect, preserving lighting and shadows): <a href="http://www.acura.com/ExteriorColor.aspx?model=TL" rel="noreferrer">http://www.acura.com/ExteriorColor.aspx?model=TL</a> WITHOUT loading &amp; replacing a new image each time; I want to be able to simply change the color tone (i.e. do a pure HTML5/CSS/JS method). <strong>EDIT: This is the result I wish to achieve, not the process.</strong></p>
  
  <p>Basically I want to change the palette/tone of an image, while preserving the other aspects of the image (such as gradient, lighting, etc.).  I have gotten close, but not close enough; I've gotten to the point where I use an image mask and composite that over the original image (sort of like a transparent image overlay).  Below is some sample code (please note this is just a snippet, so it may or may not work; I am only displaying sample code so you get an idea of what I'm trying to do):</p>
  
  <pre><code>&lt;div id='mask'&gt;
      &lt;canvas id='canvas' width='100' height='100'&gt;&lt;/canvas&gt;
  &lt;/div&gt;
  &lt;button data-rgba='255,0,0,0.5'&gt;red&lt;/button&gt;
  &lt;button data-rgba='0,255,0,0.5'&gt;green&lt;/button&gt;
  
  &lt;script&gt;
  foo = {};
  foo.ctx = jQuery('#canvas')[0];
  foo.ctx_context = foo.ctx.getContext('2d');
  foo.mask = jQuery('#mask')[0];
  foo.img = new Image();
  foo.img_path = '/path/to/image_mask.png'; // 100px x 100px image
  
  foo.changeColor = function(rgba){
      foo.ctx_context.clearRect(0, 0, 100, 100);
      foo.ctx_context.fillStyle = 'rgba(' + rgba + ')';
      foo.ctx_context.fillRect(0, 0, 100, 100);
      foo.ctx_context.globalCompositeOperation = 'destination-atop';
      foo.ctx_context.drawImage(foo.img, 0, 0);
      foo.ctx_context.css({'background-image': "url(" + foo.ctx.toDataURL("image/png") + ")"});
  };
  
  jQuery("button").click(function(){
      foo.changeColor(jQuery(this).attr('data-rgba'));
  });
  &lt;/script&gt;
  </code></pre>
  
  <p>The major problem with using this approach is that the images look really flat.  There's something else missing, or the mask I'm using (which is a solid white irregular shaped image), is the wrong approach.</p>