Brad Bird
Brad Bird

Reputation: 737

HTML5 Drag and Drop from DIV to Canvas

I'm doing a music creation project for my final year at University. I have a rough idea of how to approach it but I just need a point in the right direction.

Figure 1

From the image above, this is how I thought of doing it. The canvas is broken into squares and mapped into a JavaScript 2D array storing [FirstLine][FirstSquare] -> [FirstLine][SecondSquare] etc.. Until it reaches the second line and will then look like [SecondLine][FirstSquare] etc... You get the point. The problem I have is how to use the HTML drag and drop functions to get the DIVs on the right to be dragged into a grid square and replace that array index with the ID of the DIV. I'm not even sure if it is possible but thought I'd ask. If it's not possible then another apporach would be greatly appreciated.

Upvotes: 3

Views: 3165

Answers (1)

bennedich
bennedich

Reputation: 12367

It is most definitely possible and won't require much code either. Add the 'drop' event listener to your canvas. The event callback function will have a parameter, an event object, which contains the properties 'clientX' and 'clientY'. These are the coordinates of the mouse cursor from the canvas top-left corner. Divide these coordinates by 10 (or whatever grid cell size you choose) and the integer parts will correspond to the indices in the 2d array.

Also, don't forget to add the rest of the drag/drop code. More info here:

http://html5demos.com/drag (view source)

Upvotes: 3

Related Questions