search
HomeWeb Front-endH5 TutorialBased on HTML5 Canvas: Detailed explanation of strings, paths, backgrounds, and pictures_html5 tutorial skills

The method to create a Canvas is as follows:

Copy code
The code is as follows:



Can be found at Add the alternative text when the tag is unavailable, as follows:

Copy the code
The code is as follows:


Your browser does not support the canvas element.




Currently new versions of various browsers have gradually begun to support HTML5, so before you start using it, please make sure that your browser is a new version of Chrome, Firefox or Browsers above IE9. The

tag itself does not have the ability to draw pictures. It only provides an area for JavaScript to draw images, so the drawing work needs to be completed in JavaScript. The following is the preparation work required before drawing:

Copy the code
The code is as follows:

var canvas = document.getElementById(“canvas”);
var context2D = canvas.getContext(“2d”);

First you need to get the canvas object in the web page, and then use The getContext() method gets the two-dimensional drawing object from the canvas. The parameter "2d" of the getContext() method means two dimensions (it is said that it will be expanded to three dimensions in the future, but currently the only available parameter is "2d").

The obtained Context object is a built-in object of HTML5, which contains many graphics drawing and adjustment methods. By operating it in JavaScript, you can draw the required graphics in the Canvas canvas.

String

Use the fillText() method of the Context object to draw a string in the canvas. The prototype of fillText() method is as follows:

void fillText(text, left,top, [maxWidth]);

The meaning of its four parameters is: the string to be drawn, the abscissa and ordinate of the upper left corner in the canvas when drawn into the canvas, and the maximum length of the drawn string. The maximum length maxWidth is an optional parameter.

In addition, you can adjust the font and size of the string by changing the font attribute of the Context object. The default is "10px sans-serif".

The following example displays the string "Hello Canvas!" in the canvas (the upper left corner of the string is in the center of the canvas)

Copy code
The code is as follows:


Your browser does not support the canvas element!






Path

The basic graphics of HTML5 Canvas are based on paths. Usually the moveTo(), lineTo(), rect(), arc() and other methods of the Context object are used to first trace the path points of the graphic on the canvas, and then the fill() or stroke() method is used to fill the graphic or draw according to the path points. line.

Usually, you need to call the beginPath() method of the Context object before starting to draw a path. Its function is to clear the previous path and remind the Context to start drawing a new path. Otherwise, when the stroke() method is called, all the previous paths will be drawn. The path affects the drawing effect, and also affects the performance of the web page due to repeated operations. In addition, calling the closePath() method of the Context object can explicitly close the current path, but the path will not be cleared.

Here are prototypes for some methods of drawing paths:

void moveTo(x, y);

is used to explicitly specify the starting point of the path. By default, the starting point of the first path is the (0, 0) point of the canvas, and the subsequent starting points are the end points of the previous path. The two parameters are divided into x and y coordinate values ​​representing the starting point.

void lineTo(x, y);

is used to draw a straight path from the starting point to the specified position. After the drawing is completed, the drawn starting point will move to the specified position. The parameters represent the x and y coordinate values ​​of the specified location.

void rect(left, top,width, height);

is used to draw a rectangle with a known upper left vertex position, width and height. After the drawing is completed, the drawing starting point of the Context will move to the upper left vertex of the rectangle. The parameters represent the x and y coordinates of the upper left corner of the rectangle and the width and height of the rectangle.

void arcTo(x1, y1, x2, y2,radius);

is used to draw an arc that is tangent to two line segments. The two line segments take the current Context drawing starting point and the (x2, y2) point as the starting point, and both end at the (x1, y1) point. The arc's The radius is radius. After the drawing is completed, the drawing starting point will move to the tangent point between the line segment and the arc starting from (x2, y2).

void arc(x, y, radius,startAngle, endAngle, anticlockwise);

is used to draw an arc with the (x, y) point as the center, radius as the radius, startAngle as the starting radian, and endAngle as the ending radian. anticlockwise is a Boolean parameter, true means counterclockwise, false means clockwise. The two radians in the parameters are represented by 0°, and the position is at 3 o'clock; the Math.PI value represents 180°, and the position is at 9 o'clock.

void quadraticCurveTo(cpx,cpy, x, y);

is used to draw a quadratic spline path with the current Context drawing starting point as the starting point, (cpx, cpy) point as the control point, and (x, y) point as the end point.

void bezierCurveTo(cpx1,cpy1, cpx2, cpy2, x, y);

is used to draw a Bezier curve path with the current Context drawing starting point as the starting point, (cpx1, cpy1) point and (cpx2, cpy2) point as the two control points, and (x, y) point as the end point.


After the path drawing is completed, you need to call the fill() and stroke() methods of the Context object to fill the path and draw path lines, or call the clip() method to clip the Canvas area. The prototypes of the above three methods are as follows:

void stroke();

Used to draw lines according to existing paths.

void fill();

Used to fill the area of ​​the path using the current fill style.

void clip();

Used to set the clipping area in the canvas according to the existing route. After calling the clip() method, the graphics drawing code is only effective in the clipping area and no longer affects the canvas outside the area. If the path is not drawn before the call (that is, in the default state), the resulting clipping area is the entire Canvas area.


In addition, the Context object also provides corresponding properties to adjust the line and fill styles, as shown below:

strokeStyle

The color of the line, the default is "#000000", its value can be set to CSS color value, gradient object or pattern object.

fillStyle

The fill color defaults to "#000000". Like strokeStyle, the value can also be set to a CSS color value, gradient object or pattern object.

lineWidth

The width of the line, the unit is pixels (px), the default is 1.0.

lineCap

The endpoint style of the line, there are three types to choose from: butt (none), round (round head), and square (square head). The default is butt.

lineJoin

There are three styles of turning points of lines: round (rounded corners), bevel (flat corners), and miter (sharp corners); the type is available for selection, and the default is miter.

miterLimit

A sharp program for folding sharp corners of lines, the default is 10.


The following example calls some of the above methods and properties to draw graphics:

Copy the code
The code is as follows:


Your browser does not support the canvas element!


< ;/canvas>



Canvas background

In the above example, the fillRect() method is called. In fact, the Context object has 3 methods that can draw graphics directly on the canvas without a path. It can be considered as drawing directly on the canvas background. The prototypes of these three methods are as follows:

void fillRect(left, top,width, height);

Used to fill a rectangle with the upper left corner vertex at (left, top) point, width as width and height as height using the current fillStyle (default is "#000000", black) style.

void strokeRect(left, top,width, height);

is used to draw a rectangular border with the upper left corner vertex at (left, top) point, width as width and height as height using the current line style.

void clearRect(left, top,width, height);

Used to clear all content within the rectangular area with the upper left vertex at (left, top) point, width as width and height as height.

Pictures

Context object has drawImage() method to draw external images into Canvas. The three prototypes of the drawImage() method are as follows:

drawImage(image, dx, dy);

drawImage(image, dx, dy,dw, dh);

drawImage(image, sx, sy,sw, sh, dx, dy, dw, dh);

The following figure shows the meaning of each parameter in the prototype:

Among them, the image parameter can be HTMLImageElement, HTMLCanvasElement or HTMLVideoElement. The sx and sy in the third method prototype are both 0 in the first two, and sw and sh are both the width and height of the image itself; the dw and dh in the second and third prototypes are also both in the first one. are the width and height of the image itself.

The following example draws a remote image into the canvas:

Copy the code
The code is as follows:


Your browser does not support the canvas element!






The above code is passed through Google Chrome 14.0 and Mozilla Firefox 7.0 browser test.
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
php怎么将16进制字符串转为数字php怎么将16进制字符串转为数字Oct 26, 2021 pm 06:36 PM

php将16进制字符串转为数字的方法:1、使用hexdec()函数,语法“hexdec(十六进制字符串)”;2、使用base_convert()函数,语法“bindec(十六进制字符串, 16, 10)”。

php怎么将字符串转换成小数php怎么将字符串转换成小数Mar 22, 2023 pm 03:22 PM

PHP 是一门功能强大的编程语言,广泛应用于 Web 开发领域。其中一个非常常见的情况是需要将字符串转换为小数。这在进行数据处理的时候非常有用。在本文中,我们将介绍如何在 PHP 中将字符串转换为小数。

golang怎么检测变量是否为字符串golang怎么检测变量是否为字符串Jan 06, 2023 pm 12:41 PM

检测变量是否为字符串的方法:1、利用​“%T”格式化标识,语法“fmt.Printf("variable count=%v is of type %T \n", count, count)”;2、利用reflect.TypeOf(),语法“reflect.TypeOf(变量)”;3、利用reflect.ValueOf().Kind()检测;4、使用类型断言,可以对类型进行分组。

php 字符串长度不一致怎么办php 字符串长度不一致怎么办Feb 07, 2023 am 09:58 AM

php字符串长度不一致的解决办法:1、通过mb_detect_encoding()函数查看字符串的编码方式;2、通过mb_strlen函数查看具体字符长度;3、使用正则表达式“preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str1, $matches);”剔除非中文字符即可。

go语言怎么删除字符串中的空格go语言怎么删除字符串中的空格Jan 17, 2023 pm 02:31 PM

删除方法:1、使用TrimSpace()函数去除字符串左右两边的空格,语法“strings.TrimSpace(str)”;2、使用Trim()函数去除字符串左右两边的空格,语法“strings.Trim(str, " ")”;3、使用Replace()函数去除字符串的全部空格,语法“strings.Replace(str, " ", "", -1)”。

php字符串函数学习:怎么去掉前面的字符php字符串函数学习:怎么去掉前面的字符Mar 20, 2023 pm 02:33 PM

在开发PHP应用程序时,有时我们需要去掉字符串前面的某些特定字符或者字符串。在这种情况下,我们需要使用一些PHP函数来实现这一目标。本文将介绍一些PHP函数,帮助您轻松地去掉字符串前面的字符或字符串。

php怎么将字符串转为布尔类型php怎么将字符串转为布尔类型Jul 01, 2021 pm 06:36 PM

转换方法:1、在转换变量前加上用括号括起来的目标类型“(bool)”或“(boolean)”;2、用boolval()函数,语法“boolval(字符串)”;3、用settype()函数,语法“settype(变量,"boolean")”。

php字符串部分乱码怎么办php字符串部分乱码怎么办Jan 20, 2023 am 10:18 AM

php字符串部分乱码的解决办法:1、使用“mb_substr(strip_tags($str),0,-1,'UTF-8');”截取字符串;2、使用“iconv("UTF-8","GB2312//IGNORE",$data)”转换字符集即可。

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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),