PK creative Spring Festival, I am participating in the “Spring Festival creative submission contest”, please see: Spring Festival creative submission Contest

Everyone is writing articles about the New Year, if I do not write, IT will seem that I am not fashionable. Ice-sugar gourd is indispensable for the New Year, so I will draw a ice-sugar gourd on canvas

The specific code is as follows:

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sugar-coated berry</title>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>

<script>
  var can = document.getElementById('canvas');
  var context = can.getContext('2d');

  context.fillStyle = 'red';

  function drawCircle(x,y){
    context.beginPath();
    context.arc(x+80,y+80.45.0.2*Math.PI,false)
    context.closePath();
    context.fill();
  }

  for(var i=0; i<4; i++){ drawCircle(200.20+i*80);
  }

  // Draw the handle of ice sugar gourd
  context.fillStyle = '#d2af23';
  / / x, y, width, height
  context.fillRect(270,i*96.20.160)

  context.fillStyle = '#2c2c2c';
  / / x, y, width, height
  context.font = "28px serif";
  context.fillText("Tiger".270,i*28.160)
  context.fillStyle = '#2c2c2c';
  / / x, y, width, height
  context.fillText("Tiger".270,i*48.160)
  context.fillStyle = '#2c2c2c';
  / / x, y, width, height
  context.fillText("Raw".270,i*68.160)
  context.fillStyle = '#2c2c2c';
  / / x, y, width, height
  context.fillText("Wei".270,i*88.160)
</script>
</body>
</html>
Copy the code

Effect:

This is mainly thanks to Canvas, which provides JavaScript to draw on the canvas tag of HTML. It can be said that canvas is very powerful. Canvas mainly focuses on the production of 2D graphics.

The for loop calls the circle drawing method four times. The circle drawing method is arc(), which takes six arguments:

ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);

X represents the X-axis coordinates of the center of the circle, y represents the Y-axis coordinates of the center of the circle, radius represents the radius, startAngle represents the beginning of the arc, endAngle represents the end point, anticlockwise

Indicates counterclockwise or clockwise, the default is false, clockwise

The fillRect method is used to draw rectangles:

fillRect(x, y, width, height);

X and y are the positions of the points in the upper left corner, width is the width of the rectangle, and height is the height of the rectangle

Draw a rectangle through fillRect and then color it so that the grip of the ice sugar gourd is drawn

FillText means write

fillText(text, x, y, [maxWidth]);

Text is the font content, x represents the X-axis position of the text starting point, y represents the Y-axis position of the text starting point, and maxWidth is the optional content representing the maximum width to draw.

Good code is actually very simple answer, I wish everyone a happy New Year, life as sweet as ice sugar gourd, tiger tiger alive and powerful!