如果在画布中单击图像则发出警报

时间:2015-03-18 15:40:07

标签: javascript image canvas click mouse

所以我在画布上有动画图像。它从左到右。我希望:

alert("Wokrs!");

如果我点击图片。有人知道怎么做吗?这是我的代码:

    <head>
        <script src="events.js">
        </script>
        <script src="animation.js">
        </script>
<script>
window.onload = function(){
    var events = new Events("myCanvas");
    var canvas = document.getElementById("myCanvas");
    var c = canvas.getContext("2d");
    var anim = new Animation("myCanvas");


    var image = new Image();

    anim.setDrawStage(function()
    {
        c.clearRect(0, 0, 3000, 3000);
        c.drawImage(image, anim.getFrame() - 100, Math.cos(anim.getFrame() / 25) * 60);


        if(events.getMousePos() != null) 
        {

        //Here I want to do alert("Works!"); if mouse clicked image.

        }

    });

    image.onload = function()
    {
        anim.start();
    };
    image.src = "mojaRyba.png";

    events.listen();
};

</script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>

@edit

我添加了更多代码。

1 个答案:

答案 0 :(得分:0)

您需要添加一个click事件处理程序,这是一个示例:

canvas.addEventListener("click", function(
    alert("Works!");
)