Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping Shapes and Text in HTML5 Canvas

So I have just started working with HTML5 and the Canvas element. I'm working on a project where I will be creating mind maps, and I plan to do this using the Canvas element alongside java script.

My questions is, How do I group shapes together in a canvas? I have no issues drawing shapes and text onto the canvas, and no issues dragging them around the canvas. What I would like to do is lock say a shape and text element together so that if I drag the shape, the text comes along with it.

Any ideas?

Thanks in advance.

like image 724
Adam Holmes Avatar asked Nov 08 '10 20:11

Adam Holmes


2 Answers

You probably want to use SVG instead of canvas.

  • SVG is a board upon which you stick paths, groups, etc. which you can add, modify, etc. as they remain separate entities. You can then have things like an onclick handler on an object (path, group or whatever), which makes event handling often a lot simpler than canvas. Making repeatable content is easier with SVG, too. Draw something in Inkscape and then you can just copy the SVG it produces and do whatever with it.

  • Canvas is just a canvas to paint on; each new frame you draw on top of the previous, manually - so instead of having an <ellipse> you have to call functions on your canvas's 2D context to construct every frame. No event handlers for that ellipse - you'll need to calculate if the mouse is over the ellipse manually: there is only a single element; the strokes of the paint brush on the canvas are not kept separate. For mind maps that would make it more difficult.

SVG also makes export easy and scalable which might be desirable for your purpose. Canvas would only give you a bitmap.

like image 192
Chris Morgan Avatar answered Sep 24 '22 12:09

Chris Morgan


I am a little late to the party but fwiw there is a very nice library that let's you do layers , shapes, groups and even event bindings on HTML5's canvas element called Kinetic.js

https://github.com/ericdrowell/KineticJS/

I used this to make a draggable group of shapes and text on html5 canvas with great success.

like image 21
tmaximini Avatar answered Sep 25 '22 12:09

tmaximini