亲宝软件园·资讯

展开

canvas线条实践之运动的正方形

baby_duoduo 人气:1

原理说明:

1、通过rect实现正方形的绘制;

2、save保存canvas面板的保存,restore回复保存的canvas面板到初始状态;

3、translate用于改变canvas坐标的起始位置;

4、transform用于旋转绘制的正方形;

5、正方形边框颜色通过随机数值组合rgb颜色来实现;

6、动画效果通过requestAnimationFrame来实现。

实例效果图如下:

 

外围边框正方形实现代码

function drawFrameRect() {
    ctx.beginPath();
    ctx.strokeStyle = rectColor;
    ctx.rect(centerX - rectWidth / 2,centerY - rectHeight / 2,rectWidth,rectHeight);
    ctx.stroke();
}

内部正方形实现代码

function drawInnerRect (x,y,width,height,index,direction) {
      var length = width >= height ? height / range * 0.5 : width / range * 0.5;
      var rate = 200 / width;
      if (!colorObj[index]) {
          colorObj[index] = [];
    }
      if (colorObj[index].length == 0) {
          for (var i = 0; i < length; i ++) {
            colorObj[index].push(rectColor);
          }
       }
    var randomColor = 'rgb(' + parseInt(Math.random() * 255) + ',' + parseInt(Math.random() * 255) + ',' + parseInt(Math.random() * 255) + ')';
    colorObj[index].shift();
    colorObj[index].push(randomColor);
      for (var i = 0; i < length; i ++) {
        ctx.save();
        ctx.translate(x + width / 2, y + height / 2);
        ctx.rotate(range * 0.65 * i * rate * Math.PI / 180);
        ctx.beginPath();
        if (direction == 'outer') {
            ctx.strokeStyle = colorObj[index][i];
        } else {
            var _length = colorObj[index].length;
              ctx.strokeStyle = colorObj[index][_length - i];
        }
        ctx.rect(-width / 2 + range * i, -height / 2 + range * i,width - range * i * 2,height - range * i * 2);
        ctx.stroke();
        ctx.restore();
      }
}

canvas画布定义和动画实现

function draw() {
      width = $('body').innerWidth();
      height = $('body').innerHeight();
      ctx.clearRect(0,0,width,height);
      centerX = width / 2;
      centerY = height / 2;
      canvas.width = width;
      canvas.height = height;
      drawFrameRect();
      drawInnerRect(centerX - rectWidth / 2,centerY - rectHeight / 2,rectHeight/3,rectHeight/3,0,'outer');
      drawInnerRect(centerX - rectWidth / 2,centerY - rectHeight / 6,rectHeight/3,rectHeight/3,1,'inner');
      drawInnerRect(centerX - rectWidth / 2,centerY + rectHeight / 6,rectHeight/3,rectHeight/3,2,'outer');
      drawInnerRect(centerX - rectWidth * 3 / 10,centerY - rectHeight / 2,rectHeight,rectHeight,3,'outer');
      drawInnerRect(centerX + rectWidth * 3 / 10,centerY - rectHeight / 2,rectHeight/3,rectHeight/3,4,'inner');
      drawInnerRect(centerX + rectWidth * 3 / 10,centerY - rectHeight / 6,rectHeight/3,rectHeight/3,5,'outer');
      drawInnerRect(centerX + rectWidth * 3 / 10,centerY + rectHeight / 6,rectHeight/3,rectHeight/3,6,'inner');
      requestAnimationFrame(draw);
}

实例预览地址:canvas线条实践之运动的正方形

加载全部内容

相关教程
猜你喜欢
用户评论