How to drag and drop from one HTML5 canvas to another

删除回忆录丶 提交于 2019-12-30 10:35:09

问题


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?


回答1:


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.

Contrast this with HTML or SVG where you actually change position/transform properties of a real DOM object and the watch as the visual representation of your document updates automatically.

If you have two canvases and want to drag something from one to the other, what I would do is:

  1. 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.
  2. Draw the item onto that canvas.
  3. Track the mousemove event on the document, and update the position of the canvas relative to the mouse.
  4. 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.

Though, what I'd probably really do here is use SVG. ;)




回答2:


Check this answer. It is for multiple select drag & drop, but maybe will be useful.




回答3:


Why does this need to be 2 canvases? The canvas is your drawing area, you control it. Why do you need 2?



来源:https://stackoverflow.com/questions/4599801/how-to-drag-and-drop-from-one-html5-canvas-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!