Drag objects in canvas

前端 未结 5 1363
忘了有多久
忘了有多久 2020-12-13 10:42

Im looking for an easy to use method of assigning drag behavior to multiple objects (images, shapes etc) in canvas. Does anyone have a good way or know of any libraries for

5条回答
  •  生来不讨喜
    2020-12-13 11:38

    The HTML Canvas—unlike SVG or HTML—uses a non-retained (or immediate) graphics API. This means that when you draw something (like an image) to the canvas no knowledge of that thing remains. The only thing left is pixels on the canvas, blended with all the previous pixels. You can't really drag a subset of pixels; for one thing, the pixels that were 'under' them are gone. What you would have to do is:

    1. Track the mousedown event and see if it's in the 'right' location for dragging. (You'll have to keep track of what images/objects are where and perform mouse hit detection.)
    2. As the user drags the mouse, redraw the entire canvas from scratch, drawing the image in a new location each time based on the offset between the current mouse location and the initial mousedown location.

    Some alternatives that I might suggest:

    • SVG
    • Pure HTML
    • Multiple layered canvases, and drag one transparent canvas over another.

    The HTML Canvas is good for a lot of things. User interaction with "elements" that appear to be distinct (but are not) is not one of those things.

    Update: Here are some examples showing dragging on the canvas:

    • http://developer.yahoo.com/yui/examples/dragdrop/dd-region.html
    • http://www.redsquirrel.com/dave/work/interactivecanvas/
    • http://langexplr.blogspot.com/2008/11/using-canvas-html-element.html

    None of these have created a separate library for tracking your shapes for you, however.

提交回复
热议问题