Home > Web Front-end > JS Tutorial > Canvas draws polygons

Canvas draws polygons

高洛峰
Release: 2017-02-25 16:05:11
Original
2543 people have browsed it

Rendering:

Canvas draws polygons

The code is as follows:

<!doctype html>
<html>
<head>
 <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
 <title>canvas 画多边形</title>
</head>
<body>
 <canvas id="myCanvas" width="500" height="500"></canvas>
</body>
<script>
 var canvas = document.getElementById("myCanvas");
 var ctx = canvas.getContext(&#39;2d&#39;);
 function draw(x,y,n,r){
  var i,ang;
  ang= Math.PI*2/n;
  ctx.save();
  ctx.fillStyle = &#39;rgba(255,0,0,.3)&#39;;
  ctx.strokeStyle = &#39;hsl(120,50%,50%)&#39;;
  ctx.lineWidth = 1;
  ctx.translate(x,y);
  ctx.moveTo(0,-r);
  ctx.beginPath();
  for(i=0;i<n;i++){
   ctx.rotate(ang);
   ctx.lineTo(0,-r);
  }
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
  ctx.restore();
 }
 draw(100,100,3,40); 
 draw(200,100,4,40);
 draw(300,100,5,40);
 draw(100,200,6,40);
 draw(200,200,7,40);
 draw(300,200,8,40);
</script>
</html>
Copy after login

For more articles related to canvas drawing polygons, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template