search

Beginner Canvas

Oct 12, 2016 pm 02:52 PM

The HTML5 standard has been out for a long time, but it seems that Canvas is not used in too many places now. A very important reason is that the standard of Canvas has not been completely determined and is not suitable for large-scale use in production environments. However, the advantages of Canvas are also very obvious. For example, when drawing charts containing a large number of elements, SVG is often unable to do the job due to performance issues. For example, in the lottery session of a technology sharing meeting I saw, although the effect was relatively dazzling, it was not possible because of the performance issues. Each avatar is a DOM, and the animation is controlled by CSS3, resulting in very low performance. In addition, with the improvement of hardware performance, functions such as video screenshots and image processing can gradually be implemented on web pages. Most websites use Flash, but the performance of Flash is not high on Mac computers, and you need to learn some additional knowledge. . Canvas uses JavaScript directly for drawing and is Mac-friendly, so it can be regarded as a successor to Flash.

Use Canvas

Having said so much, what exactly is Canvas?

Canvas in English means "canvas", but the Canvas mentioned here is a new element in HTML5, on which developers can draw a series of graphics. The writing method of Canvas in HTML files is very simple:

<canvas id="canvas" width="宽度" height="高度"></canvas>

The id attribute can be used by all HTML elements. The only attributes that come with Canvas are the last two (controlling width and height respectively), and nothing else. As for compatibility, CanIUse stated above that the basic functions are currently supported by 90% of the browsers used by users, so in most cases it can be used with confidence.

Beginner Canvas

Note, be sure to use the width and height properties that come with Canvas. Do not use CSS to control it, because CSS control will cause the Canvas to deform. You can try to compare it with PhptpShop. The latter changes the "image size", while the former is the correct way to change the "canvas size". For example, the picture below is a horizontal splicing of three pictures: the black box on the far left is the original picture with a size of 50px * 50px; the middle is the effect of changing the image size to 100px * 100px. The image becomes blurry, but for the image itself It is said that the coordinate range has not become larger; the rightmost one is the correct 100px * 100px Canvas.

Beginner Canvas

Canvas Most of the drawing methods have nothing to do with the tag, and you need to use JavaScript to operate them. This is the so-called Canvas API.

We first get this element:

var canvas = document.getElementById(&#39;canvas&#39;);

Then we use a method to get the entrance that can call all Canvas APIs:

var ctx = canvas.getContext(&#39;2d&#39;);

When you see 2d, are you excited and think about 3d? There is no way to write 3D, but if you want to open the door to the 3D world, you can write canvas.getContext('webgl'). However, WebGL is a set of standards based on OpenGL ES 2.0, which is completely different from this article, so it will not be discussed here.

The basic concepts in Canvas

Coordinates

are not the same as the common Cartesian coordinate system in mathematics. The coordinate system of Canvas is a common coordinate system in computers. It looks like this:

Beginner Canvas

The upper left corner of the canvas The angle is (0,0), x increases to the right, and y increases downward, and x and y are both integers (even if they are not integers during calculation, they will be treated as integers when drawing), and the unit is pixels.

Drawing

Take everyone nostalgic. I don’t know how many students have played with logo language when they were young. In it, you can control a little turtle to walk on a board, draw, pick up a pen, and put down a pen. The same is true in Canvas, you need to control the movement and drawing of a brush. However, Canvas is more advanced. You can directly use some functions to draw pictures without having to control the position of the brush.

Basic graphics in Canvas

通过上文定义的 ctx 变量可以干许多有意思的事情,我们先看看如何绘制一些基本图形。

线条

我们指定画笔移动到某一点,然后告诉画笔需要从当前这一点画到另一点。我们可以让画笔多次移动、绘制,最后统一输出到屏幕上。例子如下:

ctx.moveTo(10, 10);
ctx.lineTo(150, 50);
ctx.lineTo(10, 50);
ctx.moveTo(10, 20);
ctx.lineTo(40, 70);
ctx.stroke();

上面的代码中,lineTo 是产生线条用的函数,执行完之后画笔就移到了线条的终点。需要注意的是,线条此时并没有显示在屏幕上,必须调用 stroke 才会显示。这样设计是有道理的,因为向屏幕上输出内容需要耗费大量的资源,我们完全可以先攒够一波 lineTo,最后用 stroke 放一个大的。

路径

绘制路径非常简单,只需要先告诉 ctx 一声“我要开始画路径了”,然后通过各种方法(例如 lineTo)绘制路径。如果需要画一个封闭路径,那就最后告诉 ctx一声:“我画完了,你把它封闭起来吧。”当然,不要忘记利用 stroke 输出到屏幕上。

一个简单的例子:

ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(150, 50);
ctx.lineTo(10, 50);
ctx.closePath();
ctx.stroke();

如果我不想只描绘路径线条,而是想填充整个路径呢?可以将最后一行的 stroke 改成 fill,这样就跟使用了画图中的油漆桶一样,封闭路径里面的内容就都被填充上颜色了:

ctx.fill();

弧 / 圆形

绘制弧的函数参数比较多:

ctx.arc(圆心 x 坐标, 圆心 y 坐标, 半径, 起始角度, 终止角度, 是否为逆时针);

注意,在 Canvas 的坐标系中,角的一边是以圆心为中心的水平向右的直线。角度单位均为弧度。例如下图,确定了圆心、起始角度(图中标明的锐角)和终止角度(图中标明的钝角),方向为逆时针,于是就有了这么一个弧。如果方向为顺时针,那么就会是一个跟它互补的、非常非常大的弧……

Beginner Canvas

所以如果转了 2π 圈之后,弧就成了圆形,因此也可以使用绘制弧的方式来绘制圆形:

ctx.beginPath();
ctx.arc(圆心 x 坐标, 圆心 y 坐标, 半径, 0, Math.PI * 2, true);
ctx.closePath();

最后一个参数随便填(当然也可以不填),因为不管是顺时针还是逆时针,转了 2π 圈之后都是一个圆。

Statement
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
HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.