canvas学习笔记(七)—-裁切路径

2021-08-19 10:48:26 浏览数 (1)

clip()将当前的路径转换为裁剪路径

只能用一次,后续再用,不起作用

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>day5-1</title>
  <style type="text/css">
    canvas{border:1px solid black;}
  </style>
</head>
<body onload="draw()">
  <canvas id="tutorial" width="150" height="150">
  </canvas>
  <script type="text/javascript">
    function draw(){
      var canvas = document.getElementById('tutorial')
      if(canvas.getContext){//判断浏览器是否支持getContext属性
        var ctx = canvas.getContext('2d');
        
        ctx.fillRect(0,0,150,150);
        ctx.translate(75,75);

        ctx.beginPath();
        ctx.arc(0,0,60,0,Math.PI*2,true);
        ctx.clip();

        var lingrad = ctx.createLinearGradient(0, -75, 0, 75)//渐变位置
        lingrad.addColorStop(0,'#232256')
        lingrad.addColorStop(1,'#143778')

        ctx.fillStyle=lingrad
        ctx.fillRect(-75,-75,150,150)
        
        var f = function(a){
          setTimeout(function(){
            ctx.save();
            ctx.fillStyle = "#fff";
            ctx.translate(75-Math.floor(Math.random()*150),
                          75-Math.floor(Math.random()*150));
            drawStar(ctx,Math.floor(Math.random()*4) 2);
            ctx.restore();
          },100*a)
        }

        for(var j=0;j<100;j  ){
          f(j)
        }

        function drawStar(ctx,r){
          ctx.save();
          ctx.beginPath();
          ctx.moveTo(r,0);
          for(var i=0;i<9;i  ){
            ctx.rotate(Math.PI/5);
            if(i%2==0){
              ctx.lineTo((r/0.525731)*0.200811,0);
            }else{
              ctx.lineTo(r,0);
            }
          }
          ctx.closePath();
          ctx.fill();
          ctx.restore();
        }
      }else{}
    }
  </script>
</body>
</html>

0 人点赞