开发者

Bind event to shape on canvas

开发者 https://www.devze.com 2022-12-29 12:43 出处:网络
How can I bind an event to a shape drawn on a canvas? I presumed this would work but I get an error. <html>

How can I bind an event to a shape drawn on a canvas? I presumed this would work but I get an error.

<html>
    <head>
    <script type="appl开发者_StackOverflow中文版ication/javascript">
    function draw() {   
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");      
        ctx.fillStyle = "rgb(200,0,0)";
        var rec = ctx.fillRect (0, 0, 55, 50);

        rec.onclick = function(){
            alert('something');
        }
    }
    </script>
    </head>
    <body onLoad="draw()">
        <canvas id="canvas" width="300" height="300"></canvas>
    </body>
</html>


Put the event handlers on the canvas element, and then use the mouse position to decide which conceptual part of the canvas the event is occurring on.

I haven't played with canvas all that much, but I wouldn't be surprised if there were already some libraries that help you manage event delegation to such imaginary elements.


Using Kineticsjs, you can handle shape events in a canvas as follows:

<script>
  shape.on('mousedown mouseover' function(evt) {
    // do something
  });
</script>


Sounds like you should be using svg instead since it allows you to add event listeners on shapes. I'd recommend checking out raphaeljs.com for a start.

0

精彩评论

暂无评论...
验证码 换一张
取 消