此代码可以正常运行:
<script type="text/javascript">
var canvas = document.createElement("canvas");
canvas.id = "myCanvas";
canvas.style.height = "640px";
canvas.style.width = "384px";
canvas.style.position = "absolute";
canvas.style.border = "1px solid black";
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
var imgd = context.getImageData(mousePos.x, mousePos.y, 1, 1);
var pix = imgd.data;
document.getElementById("listener").innerHTML = "<b><i>" + message + "<br>" + pix[3] + "</i></b>";
}, false);
</script>
<div id="listener" >
</div>
它基本上将鼠标位置写入&#34;听众&#34; div和当前像素的alpha(只要没有内容,它当然是 - 0)
但是当我添加这段代码时:
var img = new Image();
img.src = 'http://www.animefighters.de/images/armor_leatherbelly.png';
context.drawImage(img, 0, 0);
不会发生任何事...... 我究竟做错了什么?哪里出错了? 我想在画布上绘制一些图像,然后获取像素数据(包括像素的鼠标位置和alpha)... 我怎么能意识到这一点?
答案 0 :(得分:1)
你在尝试在加载之前在画布上绘制图像时,需要将其绘制为onload:
var img = new Image();
img.onload = function() {
context.drawImage(img, 0, 0);
}
img.src = 'http://www.animefighters.de/images/armor_leatherbelly.png';