Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interacting with Canvas Rectangle

I have a canvas Element in my simple HTML page and it has few rectangles drawn using context.fillRect() method. I need to interact with these drawn rectangles.

How can I do so? How can I bind onclick or onmouseover with these rectangles?

like image 763
user1039575 Avatar asked Jun 23 '11 10:06

user1039575


People also ask

Which method draws a rectangle on canvas?

To draw the rectangle onto a canvas, you can use the fill() or stroke() methods. Note: To both create and render a rectangle in one step, use the fillRect() or strokeRect() methods.

Can you style canvas with CSS?

Because the canvas is an HTML element, you can use CSS styles to modify its position, assign it a background color or image, add a border, and so on. In Safari and other WebKit-based browsers, you can use WebKit transitions to smoothly animate changes in CSS properties.


2 Answers

You'd need to keep track of the coordinates and check whether the mouse is in one of the rectangles like this: http://jsfiddle.net/eGjak/13/.

Obviously, instead of click you could also use mouseover.

var ctx = $('#cv').get(0).getContext('2d');

var rects = [[0, 0, 100, 100], [0, 150, 50, 100]]; // [x, y, width, height]
for(var i=0;i<rects.length;i++) {
    ctx.fillRect(rects[i][0], // fill at (x, y) with (width, height)
                 rects[i][1],
                 rects[i][2],
                 rects[i][3]);
}

$('#cv').click(function(e) {
    var x = e.offsetX,
        y = e.offsetY;

    for(var i=0;i<rects.length;i++) { // check whether:
        if(x > rects[i][0]            // mouse x between x and x + width
        && x < rects[i][0] + rects[i][2]
        && y > rects[i][1]            // mouse y between y and y + height
        && y < rects[i][1] + rects[i][3]) {
            alert('Rectangle ' + i + ' clicked');
        }
    }
});
like image 188
pimvdb Avatar answered Oct 08 '22 03:10

pimvdb


I've written a few tutorials on getting making and moving selectable shapes on Canvas that should give you a good understand of what you need.

The short answer is that you simply have to keep track of all of the things you want to select.

like image 43
Simon Sarris Avatar answered Oct 08 '22 04:10

Simon Sarris