canvas實現的多邊形程式碼例項

admin發表於2017-02-13

分享一段簡單的程式碼例項,它利用canvas實現了多邊形效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
var colBlock = [{
  p: [{
    x: 50,
    y: 50
  }, {
    x: 200,
    y: 50
  }, {
    x: 230,
    y: 100
  }, {
    x: 50,
    y: 200
  }],
  color: 'red'
}, {
  p: [{
    x: 200,
    y: 50
  }, {
    x: 230,
    y: 100
  }, {
    x: 400,
    y: 200
  }],
  color: 'cadetblue'
}, {
  p: [{
    x: 200,
    y: 50
  }, {
    x: 400,
    y: 200
  }, {
    x: 400,
    y: 50
  }],
  color: 'red'
}, {
  p: [{
    x: 231,
    y: 100
  }, {
    x: 50,
    y: 200
  }, {
    x: 250,
    y: 110
  }],
  color: 'cadetblue'
}, {
  p: [{
    x: 50,
    y: 200
  }, {
    x: 50,
    y: 350
  }, {
    x: 200,
    y: 350
  }, {
    x: 230,
    y: 300
  }],
  color: 'red'
}, {
  p: [{
    x: 200,
    y: 350
  }, {
    x: 400,
    y: 350
  }, {
    x: 400,
    y: 200
  }],
  color: 'red'
}, {
  p: [{
    x: 200,
    y: 350
  }, {
    x: 230,
    y: 300
  }, {
    x: 400,
    y: 200
  }],
  color: 'cadetblue'
}, {
  p: [{
    x: 50,
    y: 200
  }, {
    x: 230,
    y: 300
  }, {
    x: 250,
    y: 290
  }],
  color: 'cadetblue'
}]
 
window.onload = function() {
  var canvas = document.getElementById('canvas');
  var cxt = canvas.getContext('2d');
  for (var i = 0; i < colBlock.length; i++) {
    render(colBlock<i>, cxt)
  }
}
 
function render(col, cxt) {
  cxt.beginPath();
  cxt.moveTo(col.p[0].x, col.p[0].y);
  for (var i = 1; i < col.p.length; i++) {
    cxt.lineTo(col.p<i>.x, col.p<i>.y);
  }
 
  cxt.closePath();
  cxt.fillStyle = col.color;
  cxt.fill();
 
}  
</script>
</head>
<body>
<canvas id="canvas" width="650" height="550"></canvas>
</body>
</html>

相關文章