Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

html - HTML5 drag and drop images from a toolbar to a canvas

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...