Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
Convert image to grayscale with canvas

I'm going through a Coursera html course and I am supposed to convert an image to grayscale in one of our projects. Can somebody help explain why this doesn't work. There are ways to fix it but I want to know why when changeToGrayscale() is called and if statement is true, the for loop is not running? or if it does the image is not loaded to the canvas? Thanks in advance.

var originalImg = null;
var grayscaleImg = null;
var input;
var canvas;

function selectImage() {
    canvas = document.getElementById("canvas");
    input = document.getElementById("input");
    originalImg = new SimpleImage(input);
    originalImg.drawTo(canvas);

}

function changeToGrayscale() {

     if (imageEmpty(grayscaleImg)) {
        grayscaleImg = new SimpleImage(input);
        for (var pixel of grayscaleImg.values()) {
            var average = (pixel.getRed() + pixel.getGreen() + pixel.getBlue()) / 3;
            setRGB(average, average, average, pixel);
            grayscaleImg.setPixel(pixel.getX(), pixel.getY(), pixel);
        }

        grayscaleImg.drawTo(canvas);
    }
}

function imageEmpty(image) {
    return(image === null);
}

function setRGB(r, g, b, pixel) {
    pixel.setRed(r);
    pixel.setGreen(g);
    pixel.setBlue(b);
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!