Leo
Leo

Reputation: 150

My "changeColor" javascript function doesn't work on Google Chrome

I've a function that permits me to change the color of a PNG image:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<img id="testImage" width="400px" height="400px" style="display: none;" src='test.png'/>
<canvas id="canvas" width="400" height="400"></canvas>
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
image = document.getElementById("testImage");
ctx.drawImage(image,0,0);

var imgd = ctx.getImageData(0, 0, image.width, image.height),
pix = imgd.data,
uniqueColor = [255,255,127]; //Rossastro

// Loop lungo tutti i pixel per modificare i colori
for (var i = 0, n = pix.length; i <n; i += 4) {
    pix[i] = uniqueColor[0];   // Componente Rossa
    pix[i+1] = uniqueColor[1]; // Componente Blu
    pix[i+2] = uniqueColor[2]; // Componente Verde
    //pix[i+3] Trasparenza
}

ctx.putImageData(imgd, 0, 0);

All this code works perfectly on Mozilla Firefox, Internet Explorer 11, Microsoft Edge, but it doesn't work on Chrome and I don't know why. If I make a breakpoint to the first line of the script and then I press the resume button in the debugger, all works great.

Upvotes: 1

Views: 65

Answers (1)

epascarello
epascarello

Reputation: 207501

You are not waiting for the image to be loaded. You need to either listen to the load event on the image or the load event of the document, than fire your canvas code.

document.getElementById("testImage").addEventListener("load", function () { /* init canvas code */ } );

Upvotes: 1

Related Questions