


html5 Canvas implements drawing straight lines and setting line styles
This article mainly introduces the styles of drawing straight lines and setting lines in HTML5 Canvas. It has a certain reference value. Now I share it with you. Friends in need can refer to it
When learning to draw , lines are the most basic, and the connection of lines can form any graphics. The same is true in Canvas. Next, I will introduce you to the simplest line drawing method in detail.
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:
var cvs = document.getElementById('cvs'); //画布 var ctx = cvs.getContext('2d'); // 画笔
When we draw, 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).
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. 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 his target point.
ctx.moveTo(100,100); ctx.lineTo(200,100);
At this time, when you refresh the web page, you will find that there are no expected lines on the canvas, and there is nothing. Because we are missing one step. lineTo is actually a "path" drawn, which itself is invisible. If we want it to be displayed, we must "draw" it.
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:
ctx.moveTo(100,100); ctx.lineTo(200,100);
ctx.stroke(); Refresh at this time and you will see 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:
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. :
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 way canvas lines are drawn.
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 edges 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:
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, equal to 110.
It is for this reason that it is natural that there is a missing corner in the upper left corner. Because no one paints here.
But why are there no gaps in the remaining corners? 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:
ctx.moveTo(100,100); ctx.lineTo(200,100); ctx.moveTo(200,100); //注意这里 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 [Figure 3 ]:
明白了?因为我们把笔提起来了。
现在我们删掉moveTo,不要纠结他了,我们来思考一下如何把左上角那个缺角给补上?
首先问个问题,我们的路径闭合了吗?这不是废话么,我们不是已经把路径绕回原点了么?当然算是闭合了!
错!这样只是让路径最后一个点和起点重合了而已,路径本身却没有闭合!
Canvas怎么闭合路径?用closePath().
ctx.moveTo(100,100); ctx.lineTo(200,100); ctx.lineTo(200,200); ctx.lineTo(100,200); ctx.lineTo(100,100); ctx.closePath();//闭合路径 ctx.lineWidth = 10; ctx.strokeStyle = 'rgba(255,0,0,0.5)'; ctx.stroke();
此时刷新,就是一个完美的正方形了。图4:
无论我们把线条改到多粗————越粗越有人喜欢是吧?————这个四方形的四个角都是规矩的直角,不会出现圆滑的情况。圆滑的角是什么情况?请看PS中的四方形描边,图5:
看到了吧,越粗的边线,他的角的圆弧越大。
如果我想Canvas里面的边线也和PS这种一样,有没有办法呢?当然有,就是lineJoin属性。
lineJoin,意思即线的交汇处,有3个属性:miter(默认,尖角),bevel(斜角),round(圆角),如图6:
毫无疑问我们一下就能明白我们的矩形用的是尖角,所以试着把他改成圆角看看:
图形变成了这样,图7:
有点像PS的了吧?
另外,通过前面图我们了解到,Canvas的线条两端是平的,可不可以改呢?毕竟平的不好看。
也是可以的,即lineCap属性,这个就是定义线条的端点。lineCap有3个值:butt(平,默认),round(圆),square(方),如图8
看图就能发现,其实平头跟方头是一样的,区别只是平头没有伸出去那么一截。圆头和方头都会伸出去一截,这一节是多长呢?就是线条宽度的一半。
你有没有想到什么?哈哈,前面的闭合路径的问题,如果我们把lineCap设为方头,效果也是一样的!
但为了保险起见,我们还是要把路径闭合了,切记!
我还要提醒一下:闭合的路径没有端点!所以闭合的路径上看不到端点的样式。
另外:lineCap与lineJoin有点相似,注意不要搞混。
如果你眼尖并且运气不好,你可能会发现有时候1像素的线条不是1像素宽,好像要宽一些,模糊一些。如图9:
恭喜你!你遇到了一个不是bug的bug。这个很特别,我把他放到下一篇文章讲吧
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
HTML5 Canvas渐进填充与透明实现图像的Mask效果
The above is the detailed content of html5 Canvas implements drawing straight lines and setting line styles. For more information, please follow other related articles on the PHP Chinese website!

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



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.

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.

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.

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

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

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

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

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.
