• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

176
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);
}
almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error