如何从一个 HTML5 画布拖放到另一个
我试图弄清楚如何将图像从一个画布拖放到另一个画布.假设画布彼此相邻,是否可以无缝地将某些东西拖过边界?如果没有,将 div 拖到画布上,获取其 ID,然后通过响应画布上的 mouseup 位置来放置它是不是更好?
I'm trying to figure out how to drag and drop an image from one canvas to another canvas. Assuming the canvases are next to each other, would it be possible to seamlessly drag something across the border? If not, is it a better idea to drag a div over the canvas, get its ID, and place it by responding to the mouseup location on the canvas?
推荐答案
不要在画布上拖动项目.画布是一种非保留模式(或即时模式) 图形 API.您发出绘图命令并获得像素.模拟拖动包括跟踪用户的鼠标移动并选择反复清除并使用不同参数重新绘制画布,以使某些像素子集看起来像一个有凝聚力的对象一样移动.
You don't drag items on a canvas. A canvas is a non-retained mode (or immediate mode) graphics API. You issue draw commands and you get pixels. Simulating dragging is comprised of tracking the user's mouse movements and choosing to repeatedly clear and re-draw the canvas with different parameters to make some subset of the pixels appear to move as a cohesive object.
将此与 HTML 或 SVG 进行对比,在其中您实际上更改了真实 DOM 对象的位置/变换属性,并且当您的文档的视觉表示自动更新时,手表会自动更新.
如果你有两个画布并且想要从一个画布拖动到另一个画布,我会做的是:
If you have two canvases and want to drag something from one to the other, what I would do is:
- 将鼠标放在菜单"画布上,以编程方式创建一个与对象一样大的新画布,并(使用绝对 CSS 定位)将其放置在用户单击的项目上方.
- 将项目绘制到该画布上.
- 跟踪文档上的
mousemove
事件,并更新画布相对于鼠标的位置. - 当用户在目标画布上释放鼠标时,扔掉(或隐藏)您拖动"的小画布,并在适当位置使用拖动的项目重新绘制主画布.
- On mouse down on the 'menu' canvas, create a new canvas programmatically just as large as the object, and (using absolute CSS positioning) place it over top of the item the user clicked on.
- Draw the item onto that canvas.
- Track the
mousemove
event on the document, and update the position of the canvas relative to the mouse. - When the user releases the mouse over the destination canvas, throw away (or hide) your tiny 'dragging' canvas, and re-draw the main canvas with the item that was dragged in the appropriate location.
不过,我在这里可能真正要做的是使用 SVG.;)
Though, what I'd probably really do here is use SVG. ;)
相关文章