正如标题所说我试图裁剪图像。我占据了标签的screenshot可见区域(使用Google Chrome扩展程序中的方法)。然后,我使用getBoundingClientRect
获取以下element的尺寸。我元素的尺寸为bottom: 253.390625, height: 125, left: 820, right: 1020, top: 128.390625, width: 200
。我的问题是让元素尺寸与我的截图对齐。我的结果看起来像http://i.imgur.com/Fd34Bub.png。正如你所看到的,我甚至不接近我想要裁剪的元素。为什么会这样?
代码
// here we create a new image
function createImage(dataURL) {
// elements dimensions
var element = elementDimensions();
// labels
var elementWidth = element.width;
var elementHeight = element.height;
// create a canvas
var canvas = createCanvas(elementWidth, elementHeight);
// get the context of your canvas
var context = canvas.getContext('2d');
// create a new image object
var croppedImage = new Image();
croppedImage.onload = function() {
// cropping
context.drawImage(croppedImage, element.x, element.y, elementWidth, elementHeight, 0, 0, elementWidth, elementHeight);
// show results
console.log(canvas.toDataURL());
};
croppedImage.src = dataURL; // screenshot (full image)
}
// creates a canvas element
function createCanvas(canvasWidth, canvasHeight) {
var canvas = document.createElement("canvas");
// size of canvas in pixels
canvas.width = canvasWidth;
canvas.height = canvasHeight;
return canvas;
}
// get element dimensions
function elementDimensions() {
// element dimensions
var element = document.getElementsByClassName("itemlist")[0].getBoundingClientRect();
return {
x: element.left,
y: element.top,
width: element.width,
height: element.height
};
}