Home Web Front-end H5 Tutorial html5 Canvas drawing tutorial (2)—Drawing straight lines and setting line styles such as color/endpoint/intersection_html5 tutorial skills

html5 Canvas drawing tutorial (2)—Drawing straight lines and setting line styles such as color/endpoint/intersection_html5 tutorial skills

May 16, 2016 pm 03:50 PM
canvas draw straight lines line

If you still don’t know what Canvas is, you can read the previous article . When learning to draw, lines are the most basic, and the connection of lines can form any graphics. The same is true in Canvas.
Before we start, let’s take out the canvas and brushes:


Copy the codeThe code is as follows:
var cvs = document.getElementById('cvs'); // Canvas
var ctx = cvs.getContext('2d'); // Brush

Let’s draw When writing, the starting point is not fixed and can change at any time. Although canvas does not determine the writing point by hand, there is a method, which is moveTo. The function of moveTo is equivalent to lifting the pen tip off the canvas and then moving it to the specified point (ie, coordinates).


Copy codeThe code is as follows:
ctx.moveTo(x,y)

No graphics will be drawn during this process, which is equivalent to you holding the pen dangling on the canvas.
But there’s no use dangling around, we have to start drawing. Let’s draw the simplest one first: a straight line
The method of drawing a straight line is lineTo. Its parameters are the same as moveTo, which is a point.
ctx.lineTo(x,y) Of course, when you draw a line, the writing point also moves, so after lineTo, the writing point becomes its target point.


Copy codeThe code is as follows:
ctx.moveTo(100,100);
ctx.lineTo(200,100);

When you refresh the webpage, you will find that there is no expected line on the canvas, nothing at all. Because we are missing one step. lineTo is actually a "path" drawn, which itself is invisible. If we want him to be displayed, we must "draw" him.
Students who have used PS will definitely know the two modes of graphics, one is fill and the other is stroke. Now that we have drawn a line, it is equivalent to drawing a path in PS. At this time, we can draw the edge of the path and the graphics will be displayed.
The canvas stroke method is stroke(). Now let us complete the code:


Copy code The code is as follows:
ctx.moveTo(100,100);
ctx.lineTo(200,100);

ctx.stroke(); Refresh at this time and you can Saw a line. Of course, you can also draw hundreds of paths continuously, and then perform the stroke action to draw hundreds of lines at once. Now let’s draw a rectangle with 4 lines:


Copy the code The code is as follows:
ctx.moveTo(100,100);
ctx.lineTo(200,100);
ctx.lineTo(200,200);
ctx.lineTo(100,200);
ctx.lineTo(100,100);
ctx.stroke();

Here we draw the entire path first and then stroke it all at once.
——–Author’s complaint: One disadvantage of Canvas drawing is that it is basically based on guessing, which is very unintuitive.
Serious reminder: The canvas drawing process (i.e. filling and stroking) is very resource-consuming. If you want to save system resources and improve efficiency, it is best to draw all paths and then fill or stroke the graphics at once.
We can see from the above graphic that the default line thickness is 1px and the line color is black. Of course we can set them, but the strange thing is that setting the line width is lineWidth, but setting the line style is called strokeStyle. Why not lineStyle? I don't know either. :


Copy code The code is as follows:
ctx.lineWidth = 10;
ctx.strokeStyle = 'rgba(255,0,0,0.5)';


The above code sets the line width to 10px and the line color to translucent red.

As shown in Figure 1, refresh it, something seems wrong! Why is there a small piece missing in the upper left corner? This is not an illusion. The reason starts with the line drawing method of canvas.
Question: If the rectangular path I draw has a width and height of 100, and my side line width is 10px, what is the overall width and height of the rectangle with the sides drawn? Is it 100 10*2=120?
If the edge is completely drawn outside the path, it will be 120. But Canvas is not. All lines in Canvas have a "middle line", which is located in the absolute middle of the line. The strokes of the line extend to both sides from the center line. For example, if your line width is 1, then the center line is at 0.5; if the width is 5, then the center line is at 2.5. When the canvas graphics are stroked, the path is aligned with the center line of the line and then stroked. As shown in Figure 2:

html5 Canvas drawing tutorial (2)—Drawing straight lines and setting line styles such as color/endpoint/intersection_html5 tutorial skills


So, when tracing, half of the line is on the outside and half is on the inside. That is, the overall width of the above rectangle is 100 (10/2)*2, which is equal to 110.
It is for this reason that the upper left It is natural for the corners to appear chipped. Because no one paints here.
But why aren’t the rest of the corners notched? Doesn't it look like there are gaps in all four corners of your picture?
That’s because I didn’t “lift” the brush when I was drawing the line. The brush was continuous, that is, there was no moveTo. If you don’t believe it, let’s moveTo now:

Copy the code
The code is as follows:

ctx. moveTo(100,100);
ctx.lineTo(200,100);
ctx.moveTo(200,100); //Pay attention here
ctx.lineTo(200,200);
ctx.lineTo(100,200);
ctx.lineTo(100,100);
ctx.lineWidth = 10;
ctx.strokeStyle = 'rgba(255,0,0,0.5)';
ctx.stroke();

We movedTo before drawing the second line, and the coordinates of moveTo did not change. It was still the same point, but after refreshing, the graph became like this [Picture 3]:


Got it? Because we lifted the pen.
Now let’s delete moveTo and stop worrying about it. Let’s think about how to fill in the missing corner in the upper left corner?
First of all, let me ask a question, is our path closed? Isn’t this nonsense? Haven’t we already circled the path back to the original point? Of course it’s closed!
Wrong! This only makes the last point of the path coincide with the starting point, but the path itself is not closed!
How to close the path in Canvas? Use closePath().

Copy the code
The code is as follows:

ctx.moveTo( 100,100);
ctx.lineTo(200,100);
ctx.lineTo(200,200);
ctx.lineTo(100,200);
ctx.lineTo(100,100);
ctx.closePath( );//Closed path
ctx.lineWidth = 10;
ctx.strokeStyle = 'rgba(255,0,0,0.5)';
ctx.stroke();

Refresh at this time and it will be a perfect square. Figure 4:


No matter how thick we make the lines - the thicker the lines, the more people like them, right? ————The four corners of this square are regular right angles and will not be rounded. What about the rounded corners? Please look at the square stroke in PS, Figure 5:


As you can see, the thicker the edge, the larger the arc of its corners.
If I want the edges in Canvas to be the same as those in PS, is there any way? Of course, it is the lineJoin attribute.
lineJoin, meaning the intersection of lines, has three attributes: miter (default, sharp corner), bevel (bevel), round (rounded corner), as shown in Figure 6:

There is no doubt that we can understand at once that our rectangle has sharp corners, so try to change it to rounded corners:
The graphic becomes like this, Figure 7:

A bit like PS, right?
In addition, from the previous picture, we know that the ends of the Canvas lines are flat. Can this be changed? After all, it’s flat and doesn’t look good.
is also possible, that is, the lineCap attribute, which defines the endpoint of the line. lineCap has 3 values: butt (flat, default), round (circle), square (square), as shown in Figure 8

You can find out by looking at the picture that actually the flat head and the square head are the same. The only difference is that the flat head does not stick out so much. Both the round head and the square head will stick out for a while. How long is this section? That's half the width of the line.
Have you thought of anything? Haha, for the previous closed path problem, if we set lineCap to a square head, the effect will be the same!
But for the sake of safety, we still have to close the path, remember!
I would also like to remind you: a closed path has no endpoints! Therefore, the endpoint style cannot be seen on a closed path.
Also: lineCap is somewhat similar to lineJoin, be careful not to confuse them.
If you have a sharp eye and are unlucky, you may find that sometimes the 1 pixel line is not 1 pixel wide, but seems wider and blurry. As shown in Figure 9:

Congratulations! You have encountered a bug that is not a bug. This is very special. I will talk about it in the next article.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the canvas arrow plug-ins? What are the canvas arrow plug-ins? Aug 21, 2023 pm 02:14 PM

The canvas arrow plug-ins include: 1. Fabric.js, which has a simple and easy-to-use API and can create custom arrow effects; 2. Konva.js, which provides the function of drawing arrows and can create various arrow styles; 3. Pixi.js , which provides rich graphics processing functions and can achieve various arrow effects; 4. Two.js, which can easily create and control arrow styles and animations; 5. Arrow.js, which can create various arrow effects; 6. Rough .js, you can create hand-drawn arrows, etc.

What are the details of the canvas clock? What are the details of the canvas clock? Aug 21, 2023 pm 05:07 PM

The details of the canvas clock include clock appearance, tick marks, digital clock, hour, minute and second hands, center point, animation effects, other styles, etc. Detailed introduction: 1. Clock appearance, you can use Canvas to draw a circular dial as the appearance of the clock, and you can set the size, color, border and other styles of the dial; 2. Scale lines, draw scale lines on the dial to represent hours or minutes. Position; 3. Digital clock, you can draw a digital clock on the dial to indicate the current hour and minute; 4. Hour hand, minute hand, second hand, etc.

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

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

uniapp implements how to use canvas to draw charts and animation effects uniapp implements how to use canvas to draw charts and animation effects Oct 18, 2023 am 10:42 AM

How to use canvas to draw charts and animation effects in uniapp requires specific code examples 1. Introduction With the popularity of mobile devices, more and more applications need to display various charts and animation effects on the mobile terminal. As a cross-platform development framework based on Vue.js, uniapp provides the ability to use canvas to draw charts and animation effects. This article will introduce how uniapp uses canvas to achieve chart and animation effects, and give specific code examples. 2. canvas

What versions of html2canvas are there? What versions of html2canvas are there? Aug 22, 2023 pm 05:58 PM

The versions of html2canvas include html2canvas v0.x, html2canvas v1.x, etc. Detailed introduction: 1. html2canvas v0.x, which is an early version of html2canvas. The latest stable version is v0.5.0-alpha1. It is a mature version that has been widely used and verified in many projects; 2. html2canvas v1.x, this is a new version of html2canvas.

What properties does tkinter canvas have? What properties does tkinter canvas have? Aug 21, 2023 pm 05:46 PM

The tkinter canvas attributes include bg, bd, relief, width, height, cursor, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertwidth, selectbackground, selectforeground, xscrollcommand attributes, etc. Detailed introduction

Where are the canvas mouse coordinates? Where are the canvas mouse coordinates? Aug 22, 2023 pm 03:08 PM

How to get mouse coordinates for canvas: 1. Create a JavaScript sample file; 2. Get a reference to the Canvas element and add a listener for mouse movement events; 3. When the mouse moves on the Canvas, the getMousePos function will be triggered; 4. Use The "getBoundingClientRect()" method obtains the position and size information of the Canvas element, and obtains the mouse coordinates through event.clientX and event.clientY.

Explore the powerful role and application of canvas in game development Explore the powerful role and application of canvas in game development Jan 17, 2024 am 11:00 AM

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

See all articles