bobcodenewbie
bobcodenewbie

Reputation: 53

Why wont colorizing an image work?

I have been having a bear of a time trying to figure out why my colorization of a PNG won't work. I want to:

  1. create a canvas.
  2. draw a rectangle in it.
  3. clip the rect, so that subsequent drawing happens INSIDE the rect.
  4. bring in a couple of shapes INSIDE the rect.
  5. bring in a PNG (with transparent areas) inside the rect as well.
  6. Colorize the Png, in which the shapes underneath shows through the transparent areas and the PNG can togle thru any color.

I got so frustrated that I kept simpifying to get to the root of the problem, until I just copied the SIMPLEST piece of code from the W3schools site, and this simple image colorization doesn't work! Why does the simple example work when I look at it on the W3site but when I copy it VERBATIM onto my computer (change image name and src) it doesn't work?

I got the latest Chrome. Here's the code from W3schools.

<!DOCTYPE html>
<html>
<body>

<img id="scream" src="supportArt/scream.jpg" alt="The Scream" width="220" height="277">
<canvas id="myCanvas" width="220" height="277" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
document.getElementById("scream").onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img, 0, 0);
    var imgData = ctx.getImageData(0, 0, c.width, c.height);
    // invert colors
    var i;
    for (i = 0; i < imgData.data.length; i += 4) {
        imgData.data[i] = 255 - imgData.data[i];
        imgData.data[i+1] = 255 - imgData.data[i+1];
        imgData.data[i+2] = 255 - imgData.data[i+2];
        imgData.data[i+3] = 150;
    }
    ctx.putImageData(imgData, 0, 0);
};
</script>

</body>
</html>

Upvotes: 0

Views: 86

Answers (1)

enthusiast
enthusiast

Reputation: 999

your code is absolutely fine for html5 supported browsers(as you mentioned you are using latest Chrome). you are facing a cross domain resource sharing (CORS)[http://www.html5rocks.com/en/tutorials/cors/] problem(though it's not a problem) while you are trying to run your html file using file://.. actually your "getImageData" will not work. the easiest solution is to host your files some where (for example box.com will also work) or if you are working locally then you may host it in IIS and browse it using http://localhost/ instead of file://. this will work fine.

Upvotes: 1

Related Questions