我正在尝试将图像加载到画布中,然后获取我在图像中单击的像素的颜色数据。
<html>
<body>
<canvas id="kartina" width="500" height="500"></canvas>
<form>
<input type="text" id="textField">
</form>
var canvas=document.getElementById("kartina");
var ctx=canvas.getContext("2d");
var textField=document.getElementById("textField");
canvas.addEventListener('click',function(event){
var x=event.x;
var y=event.y;
console.log(x);
console.log(y);
var p=canvas.getImageData(x,y,1,1);
textField.value="x: "+x+", y: "+y+", R: "+p[0]+", G: "+p[1]+", B: "+p[2];
});
var img=new Image();
img.onload=function(){
ctx.drawImage(img,0,0);
};
img.src="http://www.nasa.gov/images/content/54344main_hh46_47.highres.jpg";
</script>
</html>
getImageData()
产生此错误:Uncaught TypeError: undefined is not a function
我认为问题可能出在跨域来源安全性限制,所以我尝试从this answer添加图像加载器:
<!--added below the textField form -->
<form action='#' onsubmit="return false;">
<input type='file' id='imgfile' />
<input type='button' id='btnLoad' value='Load' onclick='loadImage();' />
</form>
//added below the opening script tag
function loadImage() {
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('imgfile');
if (!input) {
write("Um, couldn't find the imgfile element.");
}
else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.onload = imageLoaded;
img.src = fr.result;
}
function imageLoaded() {
var canvas = document.getElementById("kartina")
canvas.width = img.width;
canvas.height = img.height;
var ctxLocal = canvas.getContext("2d");
ctxLocal.drawImage(img,0,0);
alert(canvas.toDataURL("image/png"));
}
function write(x){
console.log(x);
}
}
但这给了我同样的错误。我究竟做错了什么?
最佳答案
应在画布上下文对象上调用getImageData
方法:
var p = ctx.getImageData(x, y, 1, 1);
关于javascript - getImageData给出“未定义不是函数”错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28530224/