javascript - drag image after dropping it in canvas element -
to perform drag & drop functionality, canvas element, have draw image in element of destination using line,
ctx.drawimage(imgelement,dropx, dropy);
because it's drawed, found difficulty in dragging again. it's can't make move anymore
i'm working on basis of code here : http://jsfiddle.net/m1erickson/cyur7/
what modifications have make, in order drag again dropped image?
keep in mind canvas bitmap.
once images drawn on canvas cannot repositioned.
to reposition image, must clear canvas , redraw image in new position.
to move , redraw image, need save @ least basic information image:
var image1={ x:50, y:30, image:imageobject }
you can let user drag image around canvas listening mouse events
in mousedown, check if mouse on image. if yes, start drag.
in mousemove, add distance user dragged since last mousemove images x,y position.
in mouseup, stop drag.
here's example code , demo: http://jsfiddle.net/m1erickson/l3vjk/
<!doctype html> <html> <head> <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <style> body{ background-color: ivory; } #canvas{border:1px solid red;} </style> <script> $(function(){ var canvas=document.getelementbyid("canvas"); var ctx=canvas.getcontext("2d"); var canvasoffset=$("#canvas").offset(); var offsetx=canvasoffset.left; var offsety=canvasoffset.top; var isdown=false; var startx; var starty; var imgx=50; var imgy=50; var imgwidth,imgheight; var img=new image();img.onload=start;img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png"; function start(){ imgwidth=img.width; imgheight=img.height; ctx.drawimage(img,imgx,imgy); } function handlemousedown(e){ e.preventdefault(); startx=parseint(e.clientx-offsetx); starty=parseint(e.clienty-offsety); // put mousedown stuff here if(startx>=imgx && startx<=imgx+imgwidth && starty>=imgy && starty<=imgy+imgheight){ isdown=true; } } function handlemouseup(e){ e.preventdefault(); isdown=false; } function handlemouseout(e){ e.preventdefault(); isdown=false; } function handlemousemove(e){ if(!isdown){return;} e.preventdefault(); mousex=parseint(e.clientx-offsetx); mousey=parseint(e.clienty-offsety); // put mousemove stuff here if(!isdown){return;} imgx+=mousex-startx; imgy+=mousey-starty; startx=mousex; starty=mousey; ctx.clearrect(0,0,canvas.width,canvas.height); ctx.drawimage(img,imgx,imgy); } $("#canvas").mousedown(function(e){handlemousedown(e);}); $("#canvas").mousemove(function(e){handlemousemove(e);}); $("#canvas").mouseup(function(e){handlemouseup(e);}); $("#canvas").mouseout(function(e){handlemouseout(e);}); }); // end $(function(){}); </script> </head> <body> <canvas id="canvas" width=300 height=300></canvas> </body> </html>
Comments
Post a Comment