我有一个应用程序,用户可以添加标题,我唯一的问题是我有拖放多个文本的问题。使用通常的mousedown,mousemove,mouseup事件,我只能拖放一个文本,我希望能够拖放多个文本但是我没有明确的方法解决这个问题。任何帮助将不胜感激。
更新:当我试图拖动两个文本时,我的代码搞砸了,但无论如何我都会发布它。
感谢
<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>
答案 0 :(得分:1)
听起来您通过听鼠标事件了解基本拖动,所以这里是拖动多个项目的方法的大纲:
聆听mousedown,mouseup和mousemove。
如果你在一个文本边界框内得到一个mousedown + mouseup,其间有&lt; 10px的mousemove,请选择“这个文本(也许添加它对”选定“数组的引用)
如果你得到一个mousedown,然后是10+像素的mousemove,那就是“拖动”(移动“selected”数组中的所有文本)。