2016-06-11 37 views
1

我想使图像显示为六角形。 因此我使用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> 

我做了什么错?

+0

[SVG的多边形元素工作]的可能的复制(http://stackoverflow.com/questions/2152161/working-with-svg-polygon-elements) – Cristy

+0

六边形是根svg元素,它不是多边形元素的id。 –

回答

1

你需要找到svg的中心(我认为我有那个正确但你可能想要验证)。一旦你有,你可以旋转到“看老鼠”

document.addEventListener("mousemove", function(event) { 
 

 
    var follower = document.getElementById("hexagon"); 
 

 
    // ----------------------- 
 
    // calculate the center of the hexagon 
 
    // ----------------------- 
 
    var followerCentroid = (function() { 
 
    var followerClientBox = follower.getBoundingClientRect(); 
 
    return [ 
 
     (followerClientBox.top + followerClientBox.bottom)/2, 
 
     (followerClientBox.left + followerClientBox.right)/2 
 
    ]; 
 
    })(); 
 
    // ----------------------- 
 

 
    // ----------------------- 
 
    // rotate to look at mouse 
 
    // ----------------------- 
 
    var lookAngle = Math.atan2(
 
        event.pageX - followerCentroid[1], 
 
        -(event.pageY - followerCentroid[0])) * (180/Math.PI); 
 

 
    follower.style.transform = 'rotate(' + lookAngle + 'deg)'; 
 
    // ----------------------- 
 
});
<div style="padding: 50px;"> 
 
    <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> 
 
</div>

+0

它看起来像你的多边形不在你的svg中,所以“目标有点偏离”。 – JonSG