我正在使用cropper JS裁剪我的图像。我可以获得 Canvas 的宽度和高度,但是需要知道裁剪图像的坐标(X 和 Y)。
这是我的代码-
(function () {
//getting ratio
function getImageRatio(sourceCanvas) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var width = sourceCanvas.width;
var height = sourceCanvas.height;
canvas.width = width;
canvas.height = height;
context.beginPath();
context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI);
context.strokeStyle = 'rgba(0,0,0,0)';
context.stroke();
context.clip();
context.drawImage(sourceCanvas, 0, 0, width, height);
return canvas;
}
window.addEventListener('DOMContentLoaded', function () {
var image = document.getElementById('image');
var button = document.getElementById('button');
var result = document.getElementById('result');
var croppable = false;
var cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 1,
built: function () {
croppable = true;
}
});
button.onclick = function () {
var croppedCanvas;
var roundedCanvas;
var roundedImage;
if (!croppable) {
return;
}
// Crop
croppedCanvas = cropper.getCroppedCanvas();
console.log(getImageRatio(croppedCanvas));
};
});
})();
任何想法,如何获取裁剪图像的坐标,以便我可以通过 PHP 裁剪该图像。
最佳答案
所以,如果我理解正确的话,您正在寻找 method 获取数据
。
它将返回这些属性,如文档所述:
x: the offset left of the cropped area
y: the offset top of the cropped area
width: the width of the cropped area
height: the height of the cropped area
rotate: the rotated degrees of the image
scaleX: the scaling factor to apply on the abscissa of the image
scaleY: the scaling factor to apply on the ordinate of the image
不过,我建议查看文档的这一部分: https://github.com/fengyuanchen/cropper#getcroppedcanvasoptions
具体来说这部分:
After then, you can display the canvas as an image directly, or use HTMLCanvasElement.toDataURL to get a Data URL, or use HTMLCanvasElement.toBlob to get a blob and upload it to server with FormData if the browser supports these APIs.
如果由于某些浏览器限制(您始终可以添加填充)而无法使用 toBlob
方法,则可以在 Canvas 上使用 toDataUrl
获取图像 (IE9+) 。并将其发送到已经裁剪好的后端服务。为此,您需要执行以下操作:
var formData = new FormData();
formData.append('image', canvas.toDataURL());
您可以在caniuse中检查formData浏览器支持
希望您觉得它有帮助!
关于javascript - 如何通过CropperJS获取裁剪图像的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38584590/