我正在尝试完成HTML5 / javascript游戏并在crome中进行测试 我指向图像以检测像素颜色在控制台中显示错误。
请告诉我这是什么以及代码中的错误。
这是代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Canvas Example 4 (Detecting Colors)</title>
<script>
window.onload = function () {
var preview = document.getElementById('preview');
var r = document.getElementById('r');
var g = document.getElementById('g');
var b = document.getElementById('b');
var a = document.getElementById('a');
var mx = document.getElementById('mx');
var my = document.getElementById('my');
var canvas = document.getElementById('myCanvas');
canvas.addEventListener('mousemove', move, false);
var c = canvas.getContext('2d');
var building = new Image()
building.src = "img/sprite1.png";
draw();
function draw () {
c.drawImage(building, 0, 0, canvas.width, canvas.height);
}
function move (e) {
mx.innerHTML = e.clientX;
my.innerHTML = e.clientY;
var img = c.getImageData(e.clientX, e.clientY, 1, 1);
var idata = img.data;
var red = idata[0];
var green = idata[1];
var blue = idata[2];
var alpha = idata[3];
r.innerHTML = red;
g.innerHTML = green;
b.innerHTML = blue;
a.innerHTML = (alpha > 0) ? alpha : 'Transparent';
var rgba='rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')';
preview.style.backgroundColor =rgba;
}
}
</script>
<style type="text/css" media="screen">
body { margin: 0px; padding: 0px; }
canvas {
border: 1px solid black;
float: left;
}
ul {
list-style: none;
margin: 10px 10px 10px 10px;
padding: 0px;
float: left;
}
ul li { font-weight: bold; }
ul li span { font-weight: normal; }
ul li #preview { width: 50px; height: 50px; border: 1px solid black; }
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="300">
Your browser doesn't include support for the canvas tag.
</canvas>
<ul>
<li><div id="preview"></div></li>
<li>Red: <span id="r">NULL</span></li>
<li>Green: <span id="g">NULL</span></li>
<li>Blue: <span id="b">NULL</span></li>
<li>Alpha: <span id="a">NULL</span></li>
<li>Mouse X: <span id="mx">NULL</span></li>
<li>Mouse Y: <span id="my">NULL</span></li>
</ul>
</body>
</html>
答案 0 :(得分:1)
本地Web服务器是一种非常有用的开发工具。
但是,如果您只想在满足CORS要求的同时测试图像,请查看dropbox.com。
如果您注册并将图片放入公用文件夹,那么您可以通过应用building.crossOrigin =“anonymous”来满足CORS限制;
答案 1 :(得分:1)
尝试使用本地Web服务器并从中提供页面 示例使用apache并将文件放在htdoc文件夹中并查找结果。