HTML5 drag and drop images from a toolbar to a canvas

泄露秘密 提交于 2019-12-17 13:25:07

问题


I have searched a lot, but I could not find a scenario which is relevant to my need. I want to drag and drop images from a toolbar to a canvas, not from a canvas to another canvas.

Please help me on this. Thanks in advance


回答1:


Demo: http://jsfiddle.net/m1erickson/2Us2S/

Use jquery-ui to create draggable elements.

$("#myToolbarImageElement").draggable();

Load these elements with data payloads which are key-value pairs.

In your case this might be an image object that you want drawn on the canvas.

$("#myToolbarImageElement").data("image",myImageObject);

Set your canvas as a drop zone:

$("#myCanvas").droppable({drop:myDropHandler});

When you drop the elements on canvas you can read the data (image) and drawImage that image to the canvas.

function myDropHandler(e,ui){
    var x = ui.offset.left - $("#myCanvas").offset.left;
    var y = ui.offset.top  - $("#myCanvas").offset.top;
    var image = ui.draggable.data("image");
    // draw on canvas
    drawImage(image,x,y);
}

Here's a nice tutorial on drag-drop elements with data payloads using jquery-ui:

http://www.elated.com/articles/drag-and-drop-with-jquery-your-essential-guide/



来源:https://stackoverflow.com/questions/21656003/html5-drag-and-drop-images-from-a-toolbar-to-a-canvas

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