简体   繁体   English

我的“ changeColor” JavaScript函数无法在Google Chrome浏览器上使用

[英]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: 我有一个允许更改PNG图像颜色的功能:

<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. 所有这些代码都可以在Mozilla Firefox, Internet Explorer 11, Microsoft Edge上完美运行, 但是在Chrome上无法运行 ,我也不知道为什么。 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. 如果在脚本的第一行设置一个断点,然后按调试器中的“恢复”按钮,则一切正常。

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 */ } );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM