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!

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

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool