How to use canvas graphics to draw
Canvas is a powerful element in HTML5, which allows us to use JavaScript to draw graphics, animations, games, etc. In this article, we will learn how to use the canvas element to draw graphics, and use specific code examples to help us understand better.
1. Preparation
Before we start, we need an HTML document that contains a canvas element. We can add the following code to the HTML file:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Canvas绘图</title> </head> <body> <canvas id="myCanvas" width="500" height="500"></canvas> <script> // 在这里编写绘图代码 </script> </body> </html>
In the above code, we added a canvas element to the body tag and assigned an id of "myCanvas". The width and height of the canvas element are set to 500 pixels each.
2. Draw graphics
In this part, we will learn how to draw different graphics on canvas through specific code examples. We will use JavaScript’s Canvas API to achieve our goals.
fillRect()
method in the Canvas API. Please see the sample code below: var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "red"; ctx.fillRect(50, 50, 200, 100);
In the above code, we first obtain the canvas element and its 2D context object. Then, we set the color of the rectangle to be filled to red, and used the fillRect()
method to draw a rectangle with a starting position of (x:50, y:50), a width of 200, and a height of 100.
beginPath()
, arc()
and ## in the Canvas API #fill()Method. Please see the sample code below:
var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.fillStyle = "blue"; ctx.arc(250, 250, 100, 0, 2*Math.PI); ctx.fill();
beginPath() method to start a new path, set the color of the circle to be filled to blue, and use the
arc() method to draw a circle with the center The position is (x:250, y:250) and the radius is 100. Finally, we fill the circle using the
fill() method.
,
moveTo(),
lineTo( in the Canvas API ) and
stroke() methods. Please see the sample code below:
var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.strokeStyle = "green"; ctx.moveTo(50, 50); ctx.lineTo(200, 200); ctx.stroke();
beginPath() method to start a new path, set the line color to green, and use the
moveTo() method to move the starting point to (x:50, y :50), use the
lineTo() method to draw a straight line to the target point (x:200, y:200). Finally, we draw the straight line using the
stroke() method.
The above are some simple examples that demonstrate how to use the canvas element and some methods in the Canvas API to draw basic graphics. By studying and practicing these examples, we can further explore and realize the potential of canvas drawing.
The above is the detailed content of Learn how to draw graphics on canvas. For more information, please follow other related articles on the PHP Chinese website!