Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing Rects on HTML5 canvas

Is it possible to store a rectangle in a variable in order to access that variable and move it around? Something like:

var rect = new Rect();
/* then in update() method */
rect.x += 5;
rect.y += 5;

Is something like this possible, or do you have to create a new rectangle using context each time? If this is the only possible way, I don't understand how you can target each rectangle drawn in the canvas. Can someone please explain this to me?

like image 938
Seany242 Avatar asked Feb 20 '23 16:02

Seany242


2 Answers

I would save a model of all the rectangles you want to draw with their coordinates. Then, you just have to listen to the mouseclick event (or mouseover event, whatever your needs) and browse through each element of your model to see if the mouse click was done inside the coordinates of a rectangle.

As the previous posters said, you have to redraw your canvas every time you want to make a change to it (although you can speed things up by redrawing only the region of interest). Hope that helps a bit!

EDIT:

you could have a rectangle object defined:

function Rectangle(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;

    this.contains = function(x, y) {
        return (x > this.x && x <= (this.x + this.w) &&
            y > this.y && y <= (this.y + this.h));
    }

    this.clone = function() {
        return new Dimension(this.x, this.y, this.w, this.h);
    }
}

and then have an array that would be your model :

var model = [];

And then add your rectangles to it:

model.push(new Rectangle(10,10,10,10));//x, y, width, height

Then, when you click on your canvas, you retrieve the mouse click coordinates from the mouse event and you loop over your array to see if the click was done inside one of the rectangles:

for (i = 0 ; i < model.length ; i++) {
 if (model[i].contains(mouseEvent.x, mouseEvent.y))
  //do something like redraw your canvas
}
like image 101
Gaet Avatar answered Feb 23 '23 04:02

Gaet


I found that this tutorial really helped me get my head around the subject.

http://simonsarris.com/blog/510-making-html5-canvas-useful

He walks through the creation of objects, keeping track of the state, handling mouse events, etc.

like image 29
WonderfulDay Avatar answered Feb 23 '23 04:02

WonderfulDay