html - Javascript set src attribute of image not working -
i'm working on code takes weather model image , tests pixel's color. here 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 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 document document.getelementbyid("map").setattribute("src", mapaddress); settimeout(2000); //load image , 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 color if (pixelcolor[0] == 255 && pixelcolor[1] == 255 && pixelcolor[2] == 255 && pixelcolor[3] == 255) { console.log("the code ran 'if' part of pixelcolor if statement."); } else { console.log("the code ran 'else' part of pixelcolor if statement."); } </script>
for reason, image supposed displayed in canvas isn't showing up. can tell me why, , how can fix it? want solutions involve html or javascript since beginner.
you need wait image load before can access it.
// use 1 of following 2 lines. var image = new image(); // or var image = document.getelementbyid("map"); // set image location. image.src = mapaddress; // setting source not mean image has loaded. image.onload = function(event){ // fires when image has loaded. points image var c = document.createelement("canvas"); // create canvas c.width = this.width; // set size match image c.height = this.height; this.ctx = c.getcontext("2d"); // 2d context this.ctx.drawimage(this, 0, 0); // draw image onto canvas try{ var imagedat = this.ctx.getimagedata(0,0,this.width,this.height); // image pixel data // can access pixel data. }catch(e){ // if runs can not access image data. alert("cross origin resticted access"); } } image.onerror = function(event){ // there error loading image. alert("image '"+this.src+"'\nfailed load!"); }
Comments
Post a Comment