我对JavaScript有疑问。我想为这个项目做这样的事情:
基本上,我想在图片中选择某种矩形。我已经有PHP用于以后处理它。我只需要得到X&作物上/左角的Y位置。这可能在JS + HTML中吗?如果是这样,怎么样?
答案 0 :(得分:1)
是的,这是可能的。 您可以为裁剪选择器创建:div元素,设置其边框并使其位置绝对。 然后你用$('#myImage')跟踪鼠标位置.mousemove();
这是一个小提琴: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>
答案 1 :(得分:-1)
尝试使用css。
这很简单:
<强> HTML 强>
<div>
<div id="crop"></div>
<img src="http://media1.santabanta.com/full1/Creative/Abstract/abstract-310v.jpg" height="350" width="400" id="img" />
</div>
<强> CSS 强>
#crop{
width:100px;
height:100px;
border: 2px solid #ff0000;
margin-left:200px;
position:absolute;
}
#img {
border: 2px solid #ff0000;
margin-top:-110px;
}
在这个小提琴中看到这个:DEMO