HTML5 canvas basic drawing: drawing Pentagram

Time:2021-4-18

<canvas></canvas>It is a new tag added in HTML5 for drawing graphics. In fact, like other tags, this tag is special in that it can obtain a canvasrenderingcontext2d object, which can be controlled by JavaScript script for drawing.

<canvas></canvas>It’s just a container for drawing graphics. In addition to ID, class, style and other attributes, there are also height and width attributes. There are three main steps in drawing on < canvas > > elements

1. Get the DOM object corresponding to the < canvas > element, which is a canvas object;
2. Call getcontext () method of canvas object to get a canvasrenderingcontext2d object;
3. Call canvasrenderingcontext2d object to draw.

Through the analysis of pentagram, we can determine the law of the coordinates of each vertex. Here, we need to pay attention to the following point: in canvas, the direction of Y axis is downward.

The corresponding codes are as follows:

JavaScript CodeCopy content to clipboard
  1. var canvas = document.getElementById(“canvas”);   
  2.     var context = canvas.getContext(“2d”);   
  3.     context.beginPath();   
  4.     //Set the coordinates of a vertex, and make the path according to the vertex  
  5.     for (var i = 0; i < 5; i++) {   
  6.         context.lineTo(Math.cos((18+i*72)/180*Math.PI)*200+200,   
  7.                         -Math.sin((18+i*72)/180*Math.PI)*200+200);   
  8.         context.lineTo(Math.cos((54+i*72)/180*Math.PI)*80+200,   
  9.                         -Math.sin((54+i*72)/180*Math.PI)*80+200);   
  10.     }   
  11.     context.closePath();   
  12.     //Set border style and fill color  
  13.     context.lineWidth=“3”;   
  14.     context.fillStyle = “#F6F152”;   
  15.     context.strokeStyle = “#F5270B”;   
  16.     context.fill();   
  17.     context.stroke();   
  18.   

The final effect is as follows

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.