【发布时间】:2019-05-21 21:19:48
【问题描述】:
我正在尝试使用html2canvas 在浏览器中捕获图像。捕获整个浏览器的图像是可行的。但我需要指定我想要捕获的x,y 开始和结束坐标。 In the docs我看到html2canvas可以接受x,y坐标:
x:默认:元素x-offset 说明:裁剪画布x-坐标
y :默认:元素y-offset 说明:裁剪画布y-坐标
将我的x,y 坐标传递给这些参数只会捕获整个窗口。
因此,我尝试捕获整个窗口,然后使用 drawImage() 从其中裁剪一个区域(在其他一些 stackoverflow 帖子中找到,不确定是哪个):
function snapImage(x1,y1,x2,y2, e){
html2canvas(document.body).then(function(canvas) {
// calc the size -- but no larger than the html2canvas size!
var width = Math.min(canvas.width,Math.abs(x2-x1));
var height = Math.min(canvas.height,Math.abs(y2-y1));
// create a new avatarCanvas with the specified size
var avatarCanvas = document.createElement('canvas');
avatarCanvas.width=width;
avatarCanvas.height=height;
avatarCanvas.id = 'avatarCanvas';
// put avatarCanvas into document body
document.body.appendChild(avatarCanvas);
// use the clipping version of drawImage to draw
// a clipped portion of html2canvas's canvas onto avatarCanvas
var avatarCtx = avatarCanvas.getContext('2d');
avatarCtx.drawImage(canvas,x1,y1,width,height,0,0,width,height);
});
}
这会绘制偏移量错误的移位图像。例如,给定以下网站:
图片取自示例:https://github.com/niklasvh/html2canvas/tree/master/examples
我标记“pluot?”区域来捕捉它:
虚线矩形是使用 js 绘制的,给定 2 个事件中的鼠标坐标:onmousedown 和 onmouseup。因为矩形绘制正确,我假设我的坐标是正确的。但是当我将这些坐标传递给上面的函数snapImage() 时,我得到了以下捕获的图像:
看起来有一个偏移量。也许drawImage() 操作的起始坐标与我的画布起始坐标不同?
编辑:
事实证明,当我进行 100% 缩放时,我的代码可以正常工作。但当我放大/缩小时却没有。
【问题讨论】:
标签: javascript html2canvas drawimage