如何使用HTML2canvas截取拖放元素的屏幕截图

how to take screenshot of dragged and dropped elements using html2canvas

本文关键字:元素 屏幕截图 拖放 截取 何使用 HTML2canvas      更新时间:2023-09-26

我正在创建一个应用程序,其中用户将图像从一个div拖放到画布中。 如何截取画布的屏幕截图以及放入该画布的图像。

<canvas class="can" > </canvas>
<div class="pictures">
   <img src="abc.jpg" />   //before dragging
   <img src="xyz.jpg" style="top: -150px" />   //after dragging and dropping into the 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();
    }
});

根据你的代码,我假设你使用的是jQueryUI。

1 $(".canvas")不存在。由于您的canvas具有类名can,因此您应该使用$("canvas")$(".can")

2 拖放只会更改元素的视觉行为,而不会更改其 DOM 结构。如果你想这样做,你应该定义一个 drop 方法,当你在上面放东西时会触发它:

$("canvas").droppable({
    drop: function(e, ui) {
        // anything here, e.g. manipulate the DOM
        // regarding this answer, you could fire canvas drawImage here
    },
    out: function(e,ui){
        $(ui.draggable).remove();
        // regarding this answer, you may need to clear the canvas and repaint, to "visually" remove the picture
    }
});

3 画布的子节点仅在浏览器不支持画布时显示,用于回退。因此,将图像附加到画布实际上没有意义。

好的,现在我们应该清楚,你忘记在 devtool 中检查 DOM 结构,只专注于绘制画布(我在这里使用本机 JS)。

var img = document.querySelector("img"); // the image you are dragging
var cvs = document.querySelector("canvas");
var ctx = cvs.getContext("2d");
// this will draw the image to canvas at its coordination (10, 10)
ctx.drawImage(img, 10, 10);

当您拖动协调信息时,您已经知道了协调信息,因此您可以将其绘制到与画布上放置的位置完全相同的位置。

提示:您甚至可以裁剪图像的一部分,缩放它,然后绘制到画布上。有关其参数的完整列表,请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage

此外,如果要将画布内容另存为二进制图像文件,可以使用cvs.toDataURL获取图像的base64字符串。

var url = cvs.toDataURL('image/png');

然后,您可以执行任何操作,例如,生成一个按钮,用户可以单击该按钮并将图像保存到他的硬盘上。

var save = document.createElement('a');
save.setAttribute('download', 'any_name.png');
save.setAttribute('href', url);
document.appendChild(save);