簡體   English   中英

HTML5 Canvas拖放多個文本

[英]HTML5 Canvas drag and drop multiple texts

我有一個用戶可以添加字幕的應用程序,唯一的問題是我在拖放多個文本時遇到問題。 使用通常的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>

聽起來像是通過聽鼠標事件來了解基本的拖動,所以這里是拖動多個項目的方法的概述:

監聽mousedown,mouseup和mousemove。

如果您在文本邊界框內獲得了mousedown + mouseup,且鼠標之間的距離小於10px,請“選擇”此文本(也許將其引用添加到“ selected”數組中)

如果您在按下鼠標鍵后跟隨10像素以上的鼠標移動,則將其“拖動”(移動“選定”數組中的所有文本)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM