3

I'm working on some code that takes a weather model image and tests a pixel's color. Here my entire code:

<html>

<head>
    <meta title="PRWW PreCast (v0.1)">
    <meta charset="UTF-8"> 
</head>

<body>

    <canvas id="canvas" width="1024px" height="764px">

        <img id="map" src=""/>

    </canvas>

    <script>

        //Time Variables
        var currentYear = new Date().getFullYear();
        var currentMonth = new Date().getMonth() + 1;
        var currentDay = new Date().getDate();
        var currentHour = new Date().getHours();
        var currentRun;

        //Formatting Time Variables for URLs
        if (currentMonth < 10) {
            currentMonth = "0" + currentMonth;
        }
        if (currentDay < 10) {
            currentDay = "0" + currentDay;
        }

        //Finding Latest Model Run      
        if (currentHour >= 0 && currentHour < 6) {
            currentRun = "00";
        }
        if (currentHour >= 6 && currentHour < 12) {
            currentRun = "06";
        }
        if (currentHour >= 12 && currentHour < 18) {
            currentRun = "12";
        }
        if (currentHour >= 18 && currentHour < 24) {
            currentRun = "18";
    }
    var currentRun = currentRun;

    //Creating URL
    var mapAddress = "http://www.tropicaltidbits.com/analysis/models/gfs/" + currentYear + currentMonth + currentDay + currentRun + "/gfs_mslp_pcpn_neus_" + 1 + ".png";

    //Insert Image to Document
    document.getElementById("map").setAttribute("src", mapAddress);

    setTimeout(2000);

    //Load Image and Get Image Data
    document.getElementById("canvas").getContext("2d").drawImage(document.getElementById("map"), 0, 0);
    document.getElementById("map").crossOrigin = "Anonymous";
    var pixelColor = document.getElementById("canvas").getContext("2d").getImageData(469,451,1,1).data;

    //Test Pixel Data for Color
    if (pixelColor[0] == 255 && pixelColor[1] == 255 && pixelColor[2] == 255 && pixelColor[3] == 255) {
        console.log("The code ran the 'if' part of the PixelColor if statement.");
    } else {
        console.log("The code ran the 'else' part of the pixelColor if statement.");
    }   

</script>

For some reason, the image that is supposed to be displayed in the canvas isn't showing up. Can anyone tell me why, and how I can fix it? I want solutions that only involve HTML or Javascript since I am a beginner.

7
  • setTimeout(2000); does nothing. The signature is setTimeout(functionToCall, milliseconds). It sets up an asynchronous call to the function you give it, X milliseconds (or so) later. Whether this relates to the image thing I have no idea, it just jumped out at me. Commented Jan 16, 2016 at 19:04
  • Could you make a fiddle or pen of this? Regarding the timeout, Im guessing you're doing this for the image to load. It's safer to use callback that checks if the image is loaded. Commented Jan 16, 2016 at 19:11
  • Is the currentRun "calculation" correct? Using your algorithm (currentRun == 18) I get an 404 error. If I use the value prior to that (currentRun == 12) there is an image. Commented Jan 16, 2016 at 19:29
  • @vandijkstef Here's the JSfiddle: jsfiddle.net/to5s4y5k Commented Jan 16, 2016 at 19:33
  • @Andreas The currentRun and mapAddress variables work perfectly when I run the code. If I print mapAddress to the console, the link to image I want comes up. Commented Jan 16, 2016 at 19:39

1 Answer 1

2

You need to wait for the image to load before you can access it.

// only use one of the following two lines.
var image = new Image();
// or 
var image = document.getElementById("map");

// set the image location.
image.src = mapAddress; // setting the source does not mean the image has loaded.
image.onload = function(event){ // fires when image has loaded. this points to the image
    var c = document.createElement("canvas");  // create a canvas
    c.width = this.width;   // set its size to match the image
    c.height = this.height;
    this.ctx = c.getContext("2d");  // get the 2D context
    this.ctx.drawImage(this, 0, 0);  // draw the image onto the canvas
    try{
        var imageDat = this.ctx.getImageData(0,0,this.width,this.height);  // get the image pixel data
        // you can now access the pixel data.


    }catch(e){
        // if this runs then you can not access the image data.
        alert("Cross origin resticted access");
    }
}
image.onerror = function(event){
    // there was an error loading the image.
    alert("Image '"+this.src+"'\nFailed to load!");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.