gpt4 book ai didi

JavaScript 图像裁剪/矩形选择图像

转载 作者:行者123 更新时间:2023-11-28 08:08:06 27 4
gpt4 key购买 nike

我有一个关于 JavaScript 的问题。我想要一个这样的项目:

enter image description here

基本上,我想要在图片中进行某种矩形选择。我已经有了 PHP 以便稍后处理它。我只需要获取裁剪左上角/左上角的 X 和 Y 位置。 JS+HTML 可以吗?如果是这样,怎么办?

最佳答案

是的,这是可能的。您可以为裁剪选择器创建一个 div 元素,设置其边框并使其位置绝对。然后使用 $('#myImage').mousemove(); 使其跟随鼠标位置

这是一个 fiddle :http://jsfiddle.net/3kCPP/2/

这是您可以测试的代码:

<html>
<body>
<div id="info">Click on the image !</div>


<div id="myContainer" style="margin-left:140px;margin-top:40px;">
<div id="myCropSelector" style="position:absolute; border:1px solid red; width:100px; height:100px;"></div>
<img id="myImage" src="https://farm6.staticflickr.com/5340/8990232431_9f7a93d3ca.jpg" alt="myImage"/>
</div>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
var $myCropSelector = $("#myCropSelector");
var $myImage = $('#myImage');
var $myContainer = $('#myContainer');

var isMouseOnImage = function (mouseEvent, $image) {
var imageOffset = $image.offset();
return event.pageX >= imageOffset.left
&& event.pageX <= imageOffset.left + $image.width()
&& event.pageY >= imageOffset.top
&& event.pageY <= imageOffset.top + $image.height();
}

/**
* Return the location inside the document and the size of the cropSelector
* if it was supposed to be centered on the mouse location.
* {
pageX: absolute screen position
pageY: absolute screen position
imgX: relative position to the image
imgY: relative position to the image
w: width of the crop
h: height of the crop
* }
}
*/
var getCropInfo = function (mouseEvent, $cropSelector, $image) {
var pageX = mouseEvent.pageX - $cropSelector.width() / 2;
var pageY = mouseEvent.pageY - $cropSelector.height() / 2;
var imageOffset = $image.offset();
return {
pageX: pageX,
pageY: pageY,
imgX: pageX - imageOffset.left,
imgY: pageY - imageOffset.top,
w: $cropSelector.width(),
h: $cropSelector.height()
};
}

$myContainer.mousemove(function (event) {

// if the mouse is on the image
if(isMouseOnImage(event, $myImage)) {

// we center the crop selector
var cropInfo = getCropInfo(event, $myCropSelector, $myImage);
$myCropSelector.css({'top': cropInfo.pageY, 'left': cropInfo.pageX});
}
});

$myContainer.click(function (event) {

// if the mouse is on the image
if(isMouseOnImage(event, $myImage)) {
var cropInfo = getCropInfo(event, $myCropSelector, $myImage);
var infoToDisplay = "";
infoToDisplay += "x:" + cropInfo.imgX + "<br />";
infoToDisplay += "y:" + cropInfo.imgY + "<br />";
infoToDisplay += "width:" + cropInfo.w + "<br />";
infoToDisplay += "height:" + cropInfo.h;
$("#info").html(infoToDisplay);
}
});
</script>
</body>
</html>

关于JavaScript 图像裁剪/矩形选择图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24591380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com