基于canvas线条绘制图形

原理说明

绘制一个正方形,正放心每条边等比例均分,具体分配多少根据自身情况而定,按照最上边边顺时针方向依次绘制线条,相邻两条边上的点依次连接,知道所有的点全部连接完便绘制完成。

示例效果图图如下

具体实现代码如下

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var range = 130;
var region = 4;
var lineColor = '#0de4cd';
var lineColor2 = '#7aea94';
var centerX = 0;
var centerY = 0;
var pointArray = [];
draw();
function draw() {
   var width = $('body').innerWidth();
   var height = $('body').innerHeight();
   ctx.clearRect(0,0,width,height);
   pointArray = [];
   centerX = width / 2;
   centerY = height / 2;
   canvas.width = width;
   canvas.height = height;
   getPoint();
   drawRect();
   drawLine();
}
function drawRect () {
   var rectSize = range * region;
   var linearGradient= ctx.createLinearGradient(centerX - rectSize / 2,centerY - rectSize / 2,rectSize,rectSize);
   linearGradient.addColorStop(0,lineColor)
   linearGradient.addColorStop(1,lineColor2)
   //添加渐变颜色
   ctx.strokeStyle=linearGradient;
   ctx.beginPath();
   ctx.moveTo(centerX - rectSize / 2,centerY - rectSize / 2);
   ctx.lineTo(centerX + rectSize / 2,centerY - rectSize / 2);
   ctx.lineTo(centerX + rectSize / 2,centerY + rectSize / 2);
   ctx.lineTo(centerX - rectSize / 2,centerY + rectSize / 2);
   ctx.closePath();
   ctx.stroke();
}
function getPoint () {
   var rectSize = range * region;
   for (var i = 0; i < 4; i ++) {
     for (var j = 0; j < range; j ++) {
          if (i == 0) {
              _pointArray.push({x:centerX - rectSize / 2 + region * j,y:centerY - rectSize / 2});
          }
          if (i == 1) {
              _pointArray.push({x:centerX + rectSize / 2,y:centerY - rectSize / 2 + region * j});
          }
          if (i == 2) {
             _pointArray.push({x:centerX + rectSize / 2 - region * j,y:centerY + rectSize / 2});
          }
          if (i == 3) {
              _pointArray.push({x:centerX - rectSize / 2,y:centerY + rectSize / 2 - region * j});
          }
      }
      pointArray.push(_pointArray);
   }
   console.log(pointArray)
}
function drawLine () {
    pointArray.forEach(function (item, index) {
        var extraArray = pointArray[index + 1] ? pointArray[index + 1] : pointArray[0];
        item.forEach(function (child, childrenIndex) {
        ctx.beginPath();
        var linearGradient= ctx.createLinearGradient(child.x,child.y,extraArray[childrenIndex].x,extraArray[childrenIndex].y);
        linearGradient.addColorStop(0,lineColor)
        linearGradient.addColorStop(1,lineColor2)
        //添加渐变颜色
        ctx.strokeStyle=linearGradient;
        //ctx.strokeStyle = lineColor;
        ctx.moveTo(child.x,child.y);
        ctx.lineTo(extraArray[childrenIndex].x,extraArray[childrenIndex].y);
        ctx.stroke();
     })
 })
}

示例预览地址:canvas线条之美 

后话

希望上述讲解能够帮助到读者!!!

猜你喜欢

转载自www.cnblogs.com/gaozhiqiang/p/11838879.html