我想使用純JavaScript從圖像中獲取像素的顏色。如何從圖像中獲取像素的顏色?
我寫這個劇本,但沒有奏效:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Get Pixel</title>
<script type='text/javascript'>
window.onload = function() {
var canvas = document.createElement("canvas");
var pic = new Image();
pic.src = 'http://i.imgur.com/hvGAPwJ.png';
pic.onload = function() {
canvas.width = pic.width;
canvas.height = pic.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(pic, 0, 0);}
var c = canvas.getContext('2d');
var p = c.getImageData(7, 7, 1, 1).data;
var hex = "RGB = " + p[0]+", "+p[1]+", "+p[2];
document.getElementById("output").innerHTML = hex;
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
如何更改代碼,你會他工作正常?
例如,對於畫面「http://i.imgur.com/hvGAPwJ.png」,結果應該是RGB = 255,255,255
注意:你應該在設置'src'之前設置'onload'](http://stackoverflow.com/questions/4776670/should-setting-an-image-src-to-data-url-be -立即可用)。 – Phrogz