在Canvas上使用带有getImageData的JavaScript颜色检测

时间:2013-02-10 00:14:59

标签: javascript html5 canvas colors getimagedata

我遇到了getImageData函数的问题。我正在尝试制作一个程序,用于检测何时出现红色并弹出警告框。我写了一个名为“collideTest”的碰撞检测功能,虽然我找不到它的任何问题,但是它没有用。我已将下面的整个代码包括在内,将其分成几个部分,以便更友好地阅读。

(function () {
    var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
    window.requestAnimationFrame = requestAnimationFrame;
})();

//========================= B E G I N =======================================

window.onload = function init() {

    var canvas = document.getElementById("canvas");
    var c = canvas.getContext("2d");

    canvas.width = 600;
    canvas.height = 600;

    render();
}

//======================== O B J E C T S =====================================

var player = {
    x: 50,
    y: 50,
    xvel: 0,
    yvel: 0,
}

//===================== I N P U T & A D J U S T ============================

var keys = [];

window.addEventListener("keydown",function(e) {
    keys[e.keyCode] = true;
});

window.addEventListener("keyup",function(e) {
    keys[e.keyCode] = false;
});

function input() {

    if (keys[37]) {
        player.xvel -= 5
    }
    if (keys[39]) {
        player.xvel += 5
    }
    if (keys[38]) {
        player.yvel -= 5
    }
    if (keys[40]) {
        player.yvel += 5
    }

    player.x += player.xvel;
    player.y += player.yvel;

    player.xvel = 0;
    player.yvel = 0;

    collideTest();

}

//======================= C O L L I S I O N ================================

function collideTest(){
    var canvas = document.getElementById("canvas");
    var c = canvas.getContext("2d");
    var whatColor = c.getImageData(player.x - 5, player.y - 5,60,60);
    for (var i = 0; i < whatColor.data.length; i += 4) {
        if (whatColor.data[i] == 255) {
            alert("red");
        }
    }
}

//========================== R E N D E R ===================================

function render(){

    var canvas = document.getElementById("canvas");
    var c = canvas.getContext("2d");

    canvas.width = 600

    input();

    c.fillStyle = "red"
    c.fillRect(300,300,50,50);

    c.fillStyle = "rgb(106,8,136)"
    c.fillRect(player.x,player.y,50,50)

    requestAnimationFrame(render);
}

当我将collideTest()中的“255”替换为“0”时,它会一遍又一遍地弹出警报,因此它不会/完全/破坏。我只是不确定发生了什么。

感谢您提供任何帮助!!

1 个答案:

答案 0 :(得分:2)

你的计算是正确的。只需将render()函数内的input()调用移动到2个矩形创建之间:

c.fillStyle = "red"
c.fillRect(300,300,50,50);

input()

c.fillStyle = "rgb(106,8,136)"
c.fillRect(player.x,player.y,50,50)

获取图像数据将获得整个画布的快照,因此如果您每次都在红色顶部绘制紫色,那么在您正在检测的坐标处总是紫色。

我可以建议使用console.log()来吐出你的结果而不是alert()吗? ;)