gpt4 book ai didi

javascript - HTML5 Canvas 拖放多个文本

转载 作者:行者123 更新时间:2023-11-28 02:05:22 25 4
gpt4 key购买 nike

我有一个应用程序,用户可以添加标题,我唯一的问题是拖放多个文本时遇到问题。使用通常的 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 的 mousemove,则“选择”此文本(可能将其引用添加到“选定”数组)

如果您按下鼠标并随后进行 10+ 像素的鼠标移动,则其为“拖动”(移动“选定”数组中的所有文本)。

关于javascript - HTML5 Canvas 拖放多个文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17864692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com