javascript - how to take screenshot of dragged and dropped elements using html2canvas -
i creating app in user drags image 1 div , drops canvas. how take screenshot of canvas along images dropped canvas.
<canvas class="can" > </canvas> <div class="pictures"> <img src="abc.jpg" /> //before dragging <img src="xyz.jpg" style="top: -150px" /> //after dragging , dropping canvas </div>
js
function call(top,this1){ // alert("hello"); if(top==0){ var clone= this1.clone(); clone.css("top","0"); clone.draggable({addclasses: true , revert: "invalid", drag:function(){ var position = $(this).position(); var top=position.top; call(top,$(this)); } }); this1.parent().prepend(clone); this1.css("position","absolute");
} }
$("img").draggable({ addclasses: true , revert: "invalid", drag: function(){ var position = $(this).position(); var top=position.top; call(top,$(this)); } } ); $(".canvas").droppable({ out: function(e,ui){ $(ui.draggable).remove(); } });
according code assume using jqueryui.
1 $(".canvas")
not exist. since canvas
has classname can
, should use $("canvas")
or $(".can")
.
2 drag/drop changes element's visual behavior, not dom structure. if want so, should define drop method, fired when drop on it:
$("canvas").droppable({ drop: function(e, ui) { // here, e.g. manipulate dom // regarding answer, fire canvas drawimage here }, out: function(e,ui){ $(ui.draggable).remove(); // regarding answer, may need clear canvas , repaint, "visually" remove picture } });
3 child nodes of canvas displayed when browser doesn't support canvas, fallback. doesn't make sense append image canvas.
ok, should clear forget inspect dom structure in devtool, focus on drawing canvas (i'm using native js here).
var img = document.queryselector("img"); // image dragging var cvs = document.queryselector("canvas"); var ctx = cvs.getcontext("2d"); // draw image canvas @ coordination (10, 10) ctx.drawimage(img, 10, 10);
you know coordination information when you're dragging it, can draw same position drop on canvas.
tips: can crop part of image, scale draw canvas. see link full list of parameters: https://developer.mozilla.org/en-us/docs/web/api/canvasrenderingcontext2d.drawimage
moreover, if want save canvas content binary image file, can use cvs.todataurl
base64 string of image.
var url = cvs.todataurl('image/png');
then can whatever want, example, generate button user can click , save image hard disk.
var save = document.createelement('a'); save.setattribute('download', 'any_name.png'); save.setattribute('href', url); document.appendchild(save);
Comments
Post a Comment