問題描述
我試圖弄清楚如何將圖像從一個畫布拖放到另一個畫布.假設(shè)畫布彼此相鄰,是否可以無縫地將某些東西拖過邊界?如果沒有,將 div 拖到畫布上,獲取其 ID,然后通過響應(yīng)畫布上的 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.您發(fā)出繪圖命令并獲得像素.模擬拖動包括跟蹤用戶的鼠標移動并選擇反復(fù)清除并使用不同參數(shù)重新繪制畫布,以使某些像素子集看起來像一個有凝聚力的對象一樣移動.
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 對象的位置/變換屬性,并且當(dāng)您的文檔的視覺表示自動更新時,手表會自動更新.
如果你有兩個畫布并且想要從一個畫布拖動到另一個畫布,我會做的是:
If you have two canvases and want to drag something from one to the other, what I would do is:
- 將鼠標放在菜單"畫布上,以編程方式創(chuàng)建一個與對象一樣大的新畫布,并(使用絕對 CSS 定位)將其放置在用戶單擊的項目上方.
- 將項目繪制到該畫布上.
- 跟蹤文檔上的
mousemove
事件,并更新畫布相對于鼠標的位置. - 當(dāng)用戶在目標畫布上釋放鼠標時,扔掉(或隱藏)您拖動"的小畫布,并在適當(dāng)位置使用拖動的項目重新繪制主畫布.
- 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. ;)
這篇關(guān)于如何從一個 HTML5 畫布拖放到另一個的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!