Basic tutorial on using JavaScript to draw graphics using Canvas
Since HTML5 has become very popular in the past two years, I did some research. Recently, I had an idea to use HTML-related functions, so I also need to learn it carefully.
I took a good look at the functions of Canvas. I feel that HTML5 is becoming more and more functional in client-side interaction. Today I took a look at Canvas drawing. Here are a few examples. Note them down for future use.
1. Use Canvas to draw a straight line:
<!doctype html> <html> <head> <meta charset="UTF-8"> </head> <style type="text/css"> canvas{border:dashed 2px #CCC} </style> <script type="text/javascript"> function $$(id){ return document.getElementById(id); } function pageLoad(){ var can = $$('can'); var cans = can.getContext('2d'); cans.moveTo(20,30);//第一个起点 cans.lineTo(120,90);//第二个点 cans.lineTo(220,60);//第三个点(以第二个点为起点) cans.lineWidth=3; cans.strokeStyle = 'red'; cans.stroke(); } </script> <body onload="pageLoad();"> <canvas id="can" width="400px" height="300px">4</canvas> </body> </html>
The two API methods used here, moveTo and lineTo are the starting and ending coordinates of the line segment respectively, and the variables are (X coordinate, Y coordinate), strokeStyle and stroke respectively. Path drawing styles and drawing paths.
2. Draw gradient lines
Gradient lines have a gradient effect in color. Of course, the gradient style can follow the direction of the path or not:
<!doctype html> <html> <head> <meta charset="UTF-8"> </head> <style type="text/css"> canvas{border:dashed 2px #CCC} </style> <script type="text/javascript"> function $$(id){ return document.getElementById(id); } function pageLoad(){ var can = $$('can'); var cans = can.getContext('2d'); cans.moveTo(0,0); cans.lineTo(400,300); var gnt1 = cans.createLinearGradient(0,0,400,300);//线性渐变的起止坐标 gnt1.addColorStop(0,'red');//创建渐变的开始颜色,0表示偏移量,个人理解为直线上的相对位置,最大为1,一个渐变中可以写任意个渐变颜色 gnt1.addColorStop(1,'yellow'); cans.lineWidth=3; cans.strokeStyle = gnt1; cans.stroke(); } </script> <body onload="pageLoad();"> <canvas id="can" width="400px" height="300px">4</canvas> </body> </html>
3. Draw a rectangle or square:
If you use HTML4, this kind of rectangular frame can only be generated using the background code. Now the Canvas function provided by HTML5 can be easily drawn, so the superiority of HTML5 is quite high.
<!doctype html> <html> <head> <meta charset="UTF-8"> </head> <style type="text/css"> canvas{border:dashed 2px #CCC} </style> <script type="text/javascript"> function $$(id){ return document.getElementById(id); } function pageLoad(){ var can = $$('can'); var cans = can.getContext('2d'); cans.fillStyle = 'yellow'; cans.fillRect(30,30,340,240); } </script> <body onload="pageLoad();"> <canvas id="can" width="400px" height="300px">4</canvas> </body> </html>
A method is used here - fillRect(). From the literal meaning, we can know that this is to fill a rectangle. The parameters here are worth explaining. fillRect(X, Y, Width, Height), this is not the same as the coordinates in mathematics. Same, please see
here for details. The X and Y here start from the starting point relative to the upper left corner of the Canvas. Remember! !
4. Draw a simple rectangular box
The above example talks about drawing a rectangular block and filling it with color. This example simply draws a rectangle without realizing the filling effect.
<!doctype html> <html> <head> <meta charset="UTF-8"> </head> <style type="text/css"> canvas{border:dashed 2px #CCC} </style> <script type="text/javascript"> function $$(id){ return document.getElementById(id); } function pageLoad(){ var can = $$('can'); var cans = can.getContext('2d'); cans.strokeStyle = 'red'; cans.strokeRect(30,30,340,240); } </script> <body onload="pageLoad();"> <canvas id="can" width="400px" height="300px">4</canvas> </body> </html>
This is very simple, just like the above example, just replace fill with stroke. See the above example for details.
5. Draw a linear gradient rectangle
Gradient is a pretty good effect of filling. Combining Example 2 and Example 3, we can create a gradient rectangle
<!doctype html> <html> <head> <meta charset="UTF-8"> </head> <style type="text/css"> canvas{border:dashed 2px #CCC} </style> <script type="text/javascript"> function $$(id){ return document.getElementById(id); } function pageLoad(){ var can = $$('can'); var cans = can.getContext('2d'); var gnt1 = cans.createLinearGradient(10,0,390,0); gnt1.addColorStop(0,'red'); gnt1.addColorStop(0.5,'green'); gnt1.addColorStop(1,'blue'); cans.fillStyle = gnt1; cans.fillRect(10,10,380,280); } </script> <body onload="pageLoad();"> <canvas id="can" width="400px" height="300px">4</canvas> </body> </html>
I won’t explain it, remember fillRect(X, Y, Width, Height) will do.
6. Fill a circle
Circles are widely used, and of course they also include ovals.
<!doctype html> <html> <head> <meta charset="UTF-8"> </head> <style type="text/css"> canvas{border:dashed 2px #CCC} </style> <script type="text/javascript"> function $$(id){ return document.getElementById(id); } function pageLoad(){ var can = $$('can'); var cans = can.getContext('2d'); cans.beginPath(); cans.arc(200,150,100,0,Math.PI*2,true); cans.closePath(); cans.fillStyle = 'green';//本来这里最初使用的是red,截图一看,傻眼了,怕上街被爱国者打啊,其实你懂的~~ cans.fill(); } </script> <body onload="pageLoad();"> <canvas id="can" width="400px" height="300px">4</canvas> </body> </html>
The usage of arc method here is arc(X,Y,Radius,startAngle,endAngle,anticlockwise), which means (center X coordinate, center Y coordinate, radius, start angle (radians), end angle radian , whether to draw clockwise); Comparison of parameters in
arc:
a, cans.arc(200,150,100,0,Math.PI,true);
c, cans.arc(200,150,100,0, Math.PI/2,true);[/code]
c、cans.arc(200,150,100,0,Math.PI/2,true);
d、cans.arc(200,150,100, 0,Math.PI/2,false);
7. Circular block
<!doctype html> <html> <head> <meta charset="UTF-8"> </head> <style type="text/css"> canvas{border:dashed 2px #CCC} </style> <script type="text/javascript"> function $$(id){ return document.getElementById(id); } function pageLoad(){ var can = $$('can'); var cans = can.getContext('2d'); cans.beginPath(); cans.arc(200,150,100,0,Math.PI*2,false); cans.closePath(); cans.lineWidth = 5; cans.strokeStyle = 'red'; cans.stroke(); } </script> <body onload="pageLoad();"> <canvas id="can" width="400px" height="300px">4</canvas> </body> </html>
I won’t explain it here. Same as the example above, lineWidth controls the width of the line.
8. Circular Gradient
<!doctype html> <html> <head> <meta charset="UTF-8"> </head> <style type="text/css"> canvas{border:dashed 2px #CCC} </style> <script type="text/javascript"> function $$(id){ return document.getElementById(id); } function pageLoad(){ var can = $$('can'); var cans = can.getContext('2d'); var gnt = cans.createRadialGradient(200,300,50,200,200,200); gnt.addColorStop(1,'red'); gnt.addColorStop(0,'green'); cans.fillStyle = gnt; cans.fillRect(0,0,800,600); } </script> <body onload="pageLoad();"> <canvas id="can" width="800px" height="600px">4</canvas> </body> </html>
What needs to be explained here is the createRadialGradient method, the parameters are (Xstart, Ystart, radiusStart, XEnd, YEnd, radiusEnd), that is to say, when it implements the gradient, Two circles are used, one is the original circle and the other is the gradient circle. In fact, this method of coordinate and radius control can achieve many styles, such as
three-dimensional circle
var gnt = cans.createRadialGradient(200,150,0,200,50,250); gnt.addColorStop(0,'red'); gnt.addColorStop(1,'#333');
The above is the JavaScript implementation The content of the basic tutorial on drawing graphics with Canvas. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

With the rapid development of science and technology and the widespread application of information technology in the field of education, Canvas, as a world-leading online learning management system, is gradually emerging in the Chinese education industry. The emergence of Canvas provides new possibilities for the reform of education and teaching methods in China. This article will explore the development trends and prospects of Canvas in China’s education sector. First of all, one of the development trends of Canvas in China’s education sector is in-depth integration. With the rapid development of cloud computing, big data and artificial intelligence, Canvas will increasingly

Understand the power and application of canvas in game development Overview: With the rapid development of Internet technology, web games are becoming more and more popular among players. As an important part of web game development, canvas technology has gradually emerged in game development, showing its powerful power and application. This article will introduce the potential of canvas in game development and demonstrate its application through specific code examples. 1. Introduction to canvas technology Canvas is a new element in HTML5, which allows us to use
