Anish Sana Anish Sana - 1 year ago 69
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


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) -


<script src=""></script>
<h1>Upload and Display an Image</h1>
<canvas id="canvas"></canvas>
<canvas id="canvas2"></canvas>
<input type="file" multiple="false" accept="image/*" id="fileInput" onchange="upload()">
<p><input type="button" value="Make Grayscale" onclick="makeGray()"></p>


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");


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


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
function inside of the
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 Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download