我正在研究一些采用天气模型图像并测试像素颜色的代码。这是我的整个代码:
<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>
由于某种原因,应该在画布中显示的图像没有显示出来。任何人都可以告诉我为什么,以及我如何解决它?我想要的解决方案只涉及HTML或Javascript,因为我是初学者。
答案 0 :(得分:2)
您需要等待图像加载才能访问它。
// 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!");
}