pr0
pr0

Reputation: 11

HTML5 Canvas drag and drop multiple texts

I have an application where the user has the ability to add captions, my only problem is that I am having problem with dragging and dropping multiple texts. With the usual mousedown, mousemove, mouseup events I am only able to drag and drop one text, I want to have the ability to drag and drop multiple texts however I don't have a clear approach to this problem. Any help would be much appreciated.

UPDATE: My code is messed up when I am trying to drag both of the texts, but I will post it anyways.

thanks

<html>
<body>
<canvas id = 'canvas'></canvas>
<textarea id = 'topCaption'></textarea>
<textarea id = 'bottomCaption'></textarea>
<script type = 'text/javascript'>


window.addEventListener('load',initCanvas,false);

function initCanvas(e)
{
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
canvas.height = 500;
canvas.width = 500;
mouse = {x:0,y:0};
dragging = false;
topCap = document.getElementById('topCaption');
bottomCap = document.getElementById('bottomCaption');
topX = 100; //top x position
topY = 100; //top y position
botX = 300; //bottom x position
botY = 300; //bottom y position
canvas.addEventListener('mousemove',MouseMove,false);
canvas.addEventListener('mouseup',MouseUp,false);
canvas.addEventListener('mousedown',MouseDown,false);
window.addEventListener('keyup',KeyUp,false);
return setInterval(keyup,10)
}
function clear()
{
context.clearRect(0,0,canvas.width,canvas.height);
}

function text(Caption,x,y)
{
context.fillStyle = '#000';
context.font = '45px Impact';        //'bold 45px impact';
context.textAlign = 'center';
context.lineCap = 'round';
context.lineJoin = 'round';
context.fill();
context.stroke();
context.fillText(Caption,x,y);
};




function MouseMove(event){
mouse.x = event.pageX - canvas.offsetLeft;
mouse.y = event.pageY - canvas.offsetTop;
if(dragging)
{
context.lineTo(mouse.x,mouse.y);
}
}



function MouseDown(event)
{
dragging = true;
setInterval(function(){
topX = mouse.x;
topY = mouse.y;
botX = mouse.x;
botY = mouse.y;
},10)
}

function MouseUp(event)
{
if(dragging)
{
dragging = false;
}
}

function KeyUp(event)
{
clear();
text(topCap.value.toUpperCase(),topX,topY);
text(bottomCap.value.toUpperCase(),botX,botY);

}



</script>
</body>
</html>

Upvotes: 1

Views: 1150

Answers (1)

markE
markE

Reputation: 105035

Sounds like you understand basic dragging by listening to mouse events, so here's the outline of a method to drag multiple items:

Listen for mousedown, mouseup and mousemove.

If you get a mousedown+mouseup inside a text boundingbox with <10px of mousemove in-between, "select" this text (maybe add its reference to a "selected" array)

If you get a mousedown followed by 10+ pixels of mousemove, its a "drag" (move all text in the "selected" array).

Upvotes: 1

Related Questions