Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Can';t动态操纵多边形的坐标_Javascript_Jquery_Html_Css_Svg - Fatal编程技术网

Javascript Can';t动态操纵多边形的坐标

Javascript Can';t动态操纵多边形的坐标,javascript,jquery,html,css,svg,Javascript,Jquery,Html,Css,Svg,我想使图像显示为六边形。 因此,我使用svg <svg id="hexagon"> <defs> <pattern id="pattern1" height="100%" width="100%" patternContentUnits="objectBoundingBox"> <image height="1" width="1" preserveAspectRatio="none" xlink:

我想使图像显示为六边形。 因此,我使用svg

    <svg id="hexagon">
      <defs>
        <pattern id="pattern1" height="100%" width="100%" patternContentUnits="objectBoundingBox">
          <image height="1" width="1" preserveAspectRatio="none" xlink:href="https://pixabay.com/static/uploads/photo/2016/01/14/01/41/image-view-1139204_960_720.jpg"/>
        </pattern>
      </defs>
      <polygon fill="url(#pattern1)" points=" 121.25 0 242.5  100 242.5 300 121.25 400 121.25 400 0 300 0 100"/>
    </svg>

现在我想根据鼠标在屏幕上的位置来操作这个svg的坐标。因此,如果鼠标光标位于屏幕右侧,则六边形的第一个点(上一个)也应位于屏幕的右边缘。否则,如果鼠标光标位于屏幕左侧,则六边形的第一个点应位于屏幕的左边缘。此上点的位置应根据鼠标光标位置动态更改

为了进行测试,我尝试了这个方法来访问这些点,但不起作用:

<script>
  var polygon = document.getElementById("hexagon");
  polygon.setAttribute("points", "0,0  100,100 200,200");
</script> 

var polygon=document.getElementById(“hexagon”);
多边形设置属性(“点”,“0,0 100100 200200”);

我做错了什么?

您需要找到svg的中心(我想我是正确的,但您可能想验证一下)。一旦你有了它,你可以旋转它到“看鼠标”

document.addEventListener(“mousemove”),函数(事件){
var follower=document.getElementById(“hexagon”);
// -----------------------
//计算六边形的中心
// -----------------------
var followerCentroid=(函数(){
var followerClientBox=follower.getBoundingClientRect();
返回[
(followerClientBox.top+followerClientBox.bottom)/2,
(followerClientBox.left+followerClientBox.right)/2
];
})();
// -----------------------
// -----------------------
//旋转以查看鼠标
// -----------------------
var lookAngle=Math.atan2(
event.pageX-followerCentroid[1],
-(event.pageY-followerCentroid[0])*(180/Math.PI);
follower.style.transform='rotate('+lookAngle+'deg');
// -----------------------
});


六边形的可能副本是根svg元素,而不是多边形元素的id。看起来您的多边形在svg中没有居中,因此“目标有点偏离”。