HTML5 Canvas basic line drawing example tutorial_html5 tutorial skills
How to draw lines? It’s almost the same as painting in reality:
1. Move the brush to the beginning of the painting
2. Determine the stopping point of the first stroke
3. After planning, select the brush (including the Thickness and color, etc.)
4. Confirm drawing
Because Canvas is based on state drawing (very important, will be explained later), the first few steps are to determine the state, and the final step will be the specific drawing.
1. Move the brush (moveTo())
We obtained the brush context before, so we take this as an example to give an example of using the modified method - context.moveTo(100,100). The meaning of this code is to move the brush to the point (100,100) (unit is px). Remember, the upper left corner of the canvas is the origin of the Cartesian coordinate system, and the positive direction of the y-axis is downward and the positive direction of the x-axis is to the right.
2. Stroke stop point (lineTo())
Similarly, context.lineTo(600,600). This sentence means to draw from the stopping point of the previous stroke to (600,600). But be clear, the moveTo() and lineTo() here are just status, it’s planning, I’m preparing to draw, I haven’t started drawing yet, it’s just a plan!
3. Select the brush
Here we only set the color and thickness of the brush.
context.lineWidth = 5, this sentence means to set the thickness of the brush (line) to 10px.
context.strokeStyle = "#AA394C", this sentence means to set the color of the brush (line) to rose red.
Because Canvas is state-based drawing, when we select the brush thickness and color, we actually also select the line thickness and color.
4. Confirm drawing
There are only two methods to confirm drawing, fill() and stroke(). Those with some basic knowledge of drawing should know that the former refers to filling and the latter refers to stroke. Since we're just drawing lines, just stroke them. Just call the code context.stroke().
Draw a line
Isn’t it just a line segment! So much nonsense! Then let's start painting.
- "zh">
- "UTF-8">
-
Start from line - "canvas-warp">
- Your browser doesn’t support Canvas? ! Change it quickly! !
- <script> </script>
- window.onload = function(){
- var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
- var context = canvas.getContext("2d");
- context.moveTo(100,100);
- context.lineTo(600,600);
- context.lineWidth = 5;
- context.strokeStyle = "#AA394C";
- context.stroke();
- }
Run result:
(My friends have always asked me what the bear is in the lower right corner of the page? Oh, I forgot to explain before, that is my anti-counterfeiting watermark!)
I also marked a page analysis diagram for your reference. .
Here I removed the width and height from the original
Summary: To set the size of the canvas, there are only two methods
1. Set in the
2. Set the properties of canvas in JS code.
How about it? Isn’t it very cool? Next we have to speed up and draw a graphic composed of multiple lines. Do you feel like you are one step closer to being an artist? Although this is just a simple line segment, this painting is only a small step for us, but it is a giant leap for mankind!
Drawing a polyline
We have successfully drawn a line segment above. So, what if I want to draw a polyline with two strokes or even many strokes?
Smart friends must have thought of it. This is not simple. Just reuse lineTo(). Next, I just drew a beautiful polyline~
- "zh">
- "UTF-8">
-
Draw a polyline - "canvas-warp">
- Your browser doesn’t support Canvas? ! Change it quickly! !
- <script> </script>
- window.onload = function(){
- var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
- var context = canvas.getContext("2d");
- context.moveTo(100,100);
- context.lineTo(300,300);
- context.lineTo(100,500);
- context.lineWidth = 5;
- context.strokeStyle = "#AA394C";
- context.stroke();
- }
Run result:
Draw multiple polylines
In the same way, what if we want to draw multiple polylines with different styles? For example, we draw three polylines here, namely red, blue, and black. Smart friends must have thought that this is not simple. You only need to pan and change the brush color. The code format is the same, just copy it. The code is as follows.
- nbsp;html>
- "zh">
- "UTF-8">
-
绘制折线 - "canvas-warp">
- 你的浏览器居然不支持Canvas?!赶快换一个吧!!
- <script> </script>
- window.onload = function(){
- var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
- var context = canvas.getContext("2d");
- context.moveTo(100,100);
- context.lineTo(300,300);
- context.lineTo(100,500);
- context.lineWidth = 5;
- context.strokeStyle = "red";
- context.stroke();
- context.moveTo(300,100);
- context.lineTo(500,300);
- context.lineTo(300,500);
- context.lineWidth = 5;
- context.strokeStyle = "blue";
- context.stroke();
- context.moveTo(500,100);
- context.lineTo(700,300);
- context.lineTo(500,500);
- context.lineWidth = 5;
- context.strokeStyle = "black";
- context.stroke();
- }
Run result:
Huh? Isn't it strange? What about red first, then blue, then black? Why is it all black? In fact, the reason here is something I have always emphasized before - Canvas is state-based drawing.
What does it mean? In fact, every time this code uses stroke(), it will draw the previously set state again. During the first stroke(), a red polyline is drawn; during the second stroke(), the previous red polyline will be redrawn, but at this time the brush has been replaced with a blue one, so draw The polylines drawn are all blue. In other words, the strokeStyle property is overridden. In the same way, when drawing for the third time, the pen color is the final black, so three black polylines will be redrawn. Therefore, the three polylines seen here are actually drawn three times, and a total of 6 polylines are drawn.
So, I want to draw three polylines, is there no other way? Is this the end of the artist’s soul? Is there no hope? No, there is a way.
Use beginPath() to start drawing
In order to prevent the drawing method from repeated drawing, we can add beginPath() before each drawing, which means that the starting point of the next drawing is the code after beginPath(). We add context.beginPath() before drawing three times.
- nbsp;html>
- "zh">
- "UTF-8">
-
绘制折线 - "canvas-warp">
- 你的浏览器居然不支持Canvas?!赶快换一个吧!!
- <script> </script>
- window.onload = function(){
- var canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 600;
- var context = canvas.getContext("2d");
- context.beginPath();
- context.moveTo(100,100);
- context.lineTo(300,300);
- context.lineTo(100,500);
- context.lineWidth = 5;
- context.strokeStyle = "red";
- context.stroke();
- context.beginPath();
- context.moveTo(300,100);
- context.lineTo(500,300);
- context.lineTo(300,500);
- context.lineWidth = 5;
- context.strokeStyle = "blue";
- context.stroke();
- context.beginPath();
- context.moveTo(500,100);
- context.lineTo(700,300);
- context.lineTo(500,500);
- context.lineWidth = 5;
- context.strokeStyle = "black";
- context.stroke();
- }
可以看到,这里得到了我们预想的结果。因为使用了beginPath(),所以这里的绘制过程如我们所想的那样,只绘制了三次,而且每次只绘制一条折线。beginPath()是绘制设置状态的起始点,它之后代码设置的绘制状态的作用域结束于绘制方法stroke()、fill()或者closePath(),至于closePath()之后会讲到。
所以我们每次开始绘制前都务必要使用beginPath(),为了代码的完整性,建议大家在每次绘制结束后使用closePath()。

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software