编程语言
首页 > 编程语言> > 【程序集】javaScript:正六边形图片裁剪

【程序集】javaScript:正六边形图片裁剪

作者:互联网

正六边形进行裁剪

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    window.onload = function(){
      var can = document.getElementById("MainWnd");
      var context_2d = can.getContext("2d");
      var image = new Image();
      image.src = "Background.png";

      image.onload=function(){
        center = new Object();
        center.x = 600/2;
        center.y = 520/2;

        var radius = 200;
        
        // 正六边形裁剪
        var ncount = 6;
        
        var points = new Array(ncount);
        GenPolygon( center, radius, ncount, points );

        context_2d.beginPath();
           
        context_2d.moveTo(points[0].x,points[0].y);
        for( i = 1; i < points.length; i++ )
        {
          context_2d.lineTo(points[i].x,points[i].y); 
        }

        // 最后封闭曲线
        context_2d.lineTo(points[0].x,points[0].y);
        context_2d.clip();
        context_2d.drawImage(image,0,0,600,520);
      }
    }

    function RotatePointByPoint( base, org, ag, point ){
      point.x = (base.x-org.x)*Math.cos(ag)-(base.y-org.y)*Math.sin(ag)+org.x;
      point.y = (base.x-org.x)*Math.sin(ag)+(base.y-org.y)*Math.cos(ag)+org.y;     
    }

    function GenPolygon( center, radius, ncount, points ){
      if( ncount < 1 )
        return;

      points[0] = new Object();
      points[0].x = center.x;
      points[0].y = center.y + radius;

      var delta = Math.PI*2 / ncount;
      var angle = delta;

      for( i = 1; i < ncount; i++ )
      {
        points[i] = new Object();
        points[i].x = 0;
        points[i].y = 0;

        RotatePointByPoint( points[0], center, angle, points[i] );
        angle = angle + delta;  
      }
          
    }    
  </script>
</head>

<body>
   <canvas id="MainWnd" width="600px" height="520px">
   </canvas>
</body>
</html>

裁剪结果:canvas还是挺好玩的
这里写图片描述

标签:裁剪,center,javaScript,ncount,2d,points,var,org,六边形
来源: https://blog.csdn.net/qq_35162107/article/details/54617119