Anish Sana Anish Sana - 1 month ago 10
HTML Question

Same JavaScript function producing different results when manually called vs through an HTML button click

I'm stuck trying to understand why the same JavaScript function in my code is producing different results when called inside a function rather than when called through an HTML button click.

Basically, I'm trying to upload an image and convert it to grayscale using Duke University's Simple Image library. These images are then displayed on two

<canvas>
elements.

This is my code (apologies for not producing a fiddle as the library I'm using cannot be included there. Here's the link to my codepen) -

HTML -

<script src="http://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js"></script>
<h1>Upload and Display an Image</h1>
<canvas id="canvas"></canvas>
<canvas id="canvas2"></canvas>
<p>Filename:
<input type="file" multiple="false" accept="image/*" id="fileInput" onchange="upload()">
</p>
<p><input type="button" value="Make Grayscale" onclick="makeGray()"></p>


CSS -

html {
margin: 10px;
}

h1 {
font-family: helvetica;
}

canvas {
width: 500px;
height: 250px;
border-style: solid;
}

#textInput {
font-size: 20px;
}


JavaScript -

var img;

function upload() {
img = new SimpleImage(fileInput);
var canvas = document.getElementById("canvas");

img.drawTo(canvas);
}

function makeGray() {
for(var pixel of img.values()) {
var avg = (pixel.getRed() + pixel.getGreen() + pixel.getBlue())/3;
pixel.setRed(avg);
pixel.setGreen(avg);
pixel.setBlue(avg);
}
var canvas = document.getElementById("canvas2");

img.drawTo(canvas);
}


This works as I can click on the
Make Grayscale
button and display the grayscale image on the second canvas after uploading it on the first canvas. However, when I get rid of the
Make Grayscale
button and call the
makeGray()
function inside of the
upload()
function, instead of posting a grayscale image it just posts the normal image on the second canvas.

I'm not sure why this is happening as there are no errors on the console. Any information on this would be great. Thanks!

Answer

Looks like there might be a race condition with the drawTo function. delaying the makeGray call seems to work for me.

here's the updated codepen: http://codepen.io/anon/pen/jrXbGL

setTimeout("makeGray()",1000);  
Comments