Home Web Front-end HTML Tutorial Beginner Canvas <Part 1 - Basics>

Beginner Canvas <Part 1 - Basics>

Oct 08, 2016 pm 02:46 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

<br/>
Copy after login

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 way Canvas is written in an HTML file is very simple:

<br/>

where the id attribute is that of all HTML elements It can be used. The only properties that come with Canvas are the last two (controlling width and height respectively), and there are no others. 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.

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.

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('canvas');<br/>

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

var ctx = canvas.getContext(' 2d');<br/>

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:

The upper left corner of the canvas It is (0,0), x increases to the right, y increases downward, and x and y are both integers (even if they are not integers during the calculation process, 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

You can do many interesting things through the ctx variable defined above. Let’s first look at how to draw some basic graphics.

Line

We specify the brush to move to a certain point, and then tell the brush to draw from the current point to another point. We can make the brush move and draw multiple times, and finally output it to the screen uniformly. An example is as follows:

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

In the above code, lineTo is a function used to generate lines. After execution, the brush moves to the end point of the line. It should be noted that the line is not displayed on the screen at this time, and stroke must be called to display it. This design makes sense, because outputting content to the screen requires a lot of resources. We can save a wave of lineTo first, and finally use stroke to put a big one.

Path

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

一个简单的例子:

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

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

ctx.fill();

弧 / 圆形

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

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

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

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

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

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


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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input? How do I use HTML5 form validation attributes to validate user input? Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What are the best practices for cross-browser compatibility in HTML5? What are the best practices for cross-browser compatibility in HTML5? Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How to efficiently add stroke effects to PNG images on web pages? How to efficiently add stroke effects to PNG images on web pages? Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

How do I use the HTML5 <time> element to represent dates and times semantically? How do I use the HTML5 <time> element to represent dates and times semantically? Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 &lt;time&gt; element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

See all articles