Table of Contents
Path
画布背景
图片
Home Web Front-end H5 Tutorial Analysis of strings, paths, backgrounds, and pictures based on HTML5 Canvas

Analysis of strings, paths, backgrounds, and pictures based on HTML5 Canvas

Jun 22, 2018 pm 03:26 PM
picture string background path

This article mainly introduces the analysis of strings, paths, backgrounds, and pictures based on HTML5 Canvas. It has certain reference value. Now I share it with everyone. Friends in need can refer to it

HTML5 A new canvas tag has been added, through which you can use JavaScript to draw images in web pages. What the label gets in the web page is a rectangular blank area, and its width and height can be adjusted through the width and height properties.

The method of creating a Canvas is as follows:

<canvas id=”canvas” width=”600” height=”400”></canvas>
Copy after login

You can add alternative text when the tag is unavailable, as shown below:

<canvas id=”canvas” width=”600” height=”400”>
         <p>Your browserdoes not support the canvas element.</p>
</canvas>
Copy after login

Currently, new versions of various browsers have gradually HTML5 is now supported, so please make sure your browser is a new version of Chrome, Firefox or IE9 or above before starting to use it.

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:

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

First, you need to obtain the canvas object in the web page, and then use the getContext() method to obtain 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. You can draw the required graphics in the Canvas canvas by operating it in JavaScript.

String

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

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

Its four parameters The meaning is divided into: 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)

<canvas id="canvas" width="600"height="400">
         <p>Your browserdoes not support the canvas element!</p>
</canvas>
<script type="text/javascript">
window.onload = function() {
         var canvas =document.getElementById("canvas");
         var context2D =canvas.getContext("2d");
         context2D.font ="35px Times New Roman";
         context2D.fillText("HelloCanvas!", canvas.width / 2, canvas.height / 2);
}
</script>
Copy after login

Path

HTML5 Canvas The basic graphics 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, it will All paths before drawing will affect the drawing effect, and also affect 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.

The following are the prototypes of some methods for drawing paths:

void moveTo(x, y);

Used to explicitly specify the path starting point. 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. Location. 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 known upper left vertex position, width and height. After the drawing is completed The drawing starting point of the Context will be moved to the upper left corner 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 are respectively Take the current Context drawing starting point and the (x2, y2) point as the starting point, both end at the (x1, y1) point, and the radius of the arc 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 a circle with (x, y) point as the center and radius as Radius, startAngle is the starting radian, endAngle is the arc of 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 with the current Context drawing starting point as the starting point, and the (cpx, cpy) point as the control point , a quadratic spline path with the (x, y) point as the end point.

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

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

路径描绘完成后,需要调用Context对象的fill()和stroke()方法来填充路径和绘制路径线条,或者调用clip()方法来剪辑Canvas区域。以上三个方法的原型如下:

void stroke();

用于按照已有的路径绘制线条。

void fill();

用于使用当前的填充风格来填充路径的区域。

void clip();

用于按照已有的路线在画布中设置剪辑区域。调用clip()方法之后,图形绘制代码只对剪辑区域有效而不再影响区域外的画布。如调用之前没有描绘路径(即默认状态下),则得到的剪辑区域为整个Canvas区域。

此外,Context对象还提供了相应的属性来调整线条及填充风格,如下所示:

strokeStyle

线条的颜色,默认为”#000000”,其值可以设置为CSS颜色值、渐变对象或者模式对象。

fillStyle

填充的颜色,默认为”#000000”,与strokeStyle一样,值也可以设置为CSS颜色值、渐变对象或者模式对象。

lineWidth

线条的宽度,单位是像素(px),默认为1.0。

lineCap

线条的端点样式,有butt(无)、round(圆头)、square(方头)三种类型可供选择,默认为butt。

lineJoin

线条的转折处样式,有round(圆角)、bevel(平角)、miter(尖角)三种;类型可供选择,默认为miter。

miterLimit

线条尖角折角的锐利程序,默认为10。

如下的示例分别调用了部分上述方法和属性来绘制图形:

<canvas id="canvas" width="600"height="400">
         <p>Your browserdoes not support the canvas element!</p>
</canvas>
<script type="text/javascript">
window.onload = function() {
         var canvas =document.getElementById("canvas");
         var context2D =canvas.getContext("2d");
         //绘制相交的线段
         context2D.beginPath();
         context2D.moveTo(50,50);
         context2D.lineTo(100,100);
         context2D.moveTo(200,50);
         context2D.lineTo(100,100);
         context2D.stroke();
         //绘制与这两条线段相切的红色圆弧
         context2D.beginPath();
         context2D.strokeStyle= "#ff0000";
         context2D.moveTo(50,50);
         context2D.arcTo(100,100, 200, 50, 100);
         context2D.stroke();
         //绘制一个蓝色的圆
         context2D.beginPath();
         context2D.strokeStyle= "#0000ff";
         context2D.arc(300,250, 100, 0, Math.PI * 2, false);
         context2D.stroke();
         //将上面的圆填充为灰色
         context2D.fillStyle ="#a3a3a3";
         context2D.fill();
         //在上面的圆中剪辑一个圆形方形区域
         context2D.beginPath();
         context2D.rect(250,200, 100, 100);
         context2D.clip();
         //在剪辑区域中填充一个大于该区域尺寸的矩形
         context2D.fillStyle ="yellow";
         context2D.fillRect(0,0, 400, 400);
}
</script>
Copy after login

画布背景

在上面的例子中,调用了fillRect()方法。实际上,Context对象拥有3个方法可以直接在画布上绘制图形而不需要路径,可以将其视为直接在画布背景中绘制。这3个方法的原型如下:

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

用于使用当前的fillStyle(默认为”#000000”,黑色)样式填充一个左上角顶点在(left, top)点、宽为width、高为height的矩形。

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

用于使用当前的线条风格绘制一个左上角顶点在(left, top)点、宽为width、高为height的矩形边框。

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

用于清除左上角顶点在(left,top)点、宽为width、高为height的矩形区域内的所有内容。

图片

Context对象中拥有drawImage()方法可以将外部图片绘制到Canvas中。drawImage()方法的3种原型如下:

drawImage(image, dx, dy);

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

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

下图展示了原型中各参数的含义:

其中,image参数可以是HTMLImageElement、HTMLCanvasElement或者HTMLVideoElement。第三个方法原型中的sx、sy在前两个中均为0,sw、sh均为image本身的宽和高;第二和第三个原型中的dw、dh在第一个中也均为image本身的宽和高。

如下的示例将一张远程图片绘制到了画布中:

<canvas id="canvas" width="600"height="400">
         <p>Your browserdoes not support the canvas element!</p>
</canvas>
<script type="text/javascript">
window.onload = function() {
         var canvas =document.getElementById("canvas");
         var context2D =canvas.getContext("2d");
         var pic = new Image();
         pic.src ="http://imgsrc.baidu.com/forum/pic/item/e6b14bc2a4561b1fe4dd3b24.jpg";
         context2D.drawImage(pic,0, 0);
}
</script>
Copy after login

以上代码均通过Google Chrome 14.0及Mozilla Firefox 7.0浏览器测试。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

HTML5 Canvas实现绘制一个像素宽的细线

The above is the detailed content of Analysis of strings, paths, backgrounds, and pictures based on HTML5 Canvas. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? Mar 22, 2024 am 08:06 AM

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the &quot;My&quot; button in the lower right corner; (2) On the personal center page, find &quot;Settings&quot; and click it; (3) Scroll down and find the &quot;Clear Cache&quot; option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? How to post pictures in TikTok comments? Where is the entrance to the pictures in the comment area? Mar 21, 2024 pm 09:12 PM

With the popularity of Douyin short videos, user interactions in the comment area have become more colorful. Some users wish to share images in comments to better express their opinions or emotions. So, how to post pictures in TikTok comments? This article will answer this question in detail and provide you with some related tips and precautions. 1. How to post pictures in Douyin comments? 1. Open Douyin: First, you need to open Douyin APP and log in to your account. 2. Find the comment area: When browsing or posting a short video, find the place where you want to comment and click the &quot;Comment&quot; button. 3. Enter your comment content: Enter your comment content in the comment area. 4. Choose to send a picture: In the interface for entering comment content, you will see a &quot;picture&quot; button or a &quot;+&quot; button, click

How to make ppt pictures appear one by one How to make ppt pictures appear one by one Mar 25, 2024 pm 04:00 PM

In PowerPoint, it is a common technique to display pictures one by one, which can be achieved by setting animation effects. This guide details the steps to implement this technique, including basic setup, image insertion, adding animation, and adjusting animation order and timing. Additionally, advanced settings and adjustments are provided, such as using triggers, adjusting animation speed and order, and previewing animation effects. By following these steps and tips, users can easily set up pictures to appear one after another in PowerPoint, thereby enhancing the visual impact of the presentation and grabbing the attention of the audience.

What should I do if the images on the webpage cannot be loaded? 6 solutions What should I do if the images on the webpage cannot be loaded? 6 solutions Mar 15, 2024 am 10:30 AM

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

How to arrange two pictures side by side in wps document How to arrange two pictures side by side in wps document Mar 20, 2024 pm 04:00 PM

When using WPS office software, we found that not only one form is used, tables and pictures can be added to the text, pictures can also be added to the table, etc. These are all used together to make the content of the entire document look richer. , if you need to insert two pictures into the document and they need to be arranged side by side. Our next course can solve this problem: how to place two pictures side by side in a wps document. 1. First, you need to open the WPS software and find the picture you want to adjust. Left-click the picture and a menu bar will pop up, select &quot;Page Layout&quot;. 2. Select &quot;Tight wrapping&quot; in text wrapping. 3. After all the pictures you need are confirmed to be set to &quot;Tight text wrapping&quot;, you can drag the pictures to the appropriate position and click on the first picture.

How to replace all ppt backgrounds How to replace all ppt backgrounds Mar 25, 2024 pm 04:25 PM

PPT background replacement is an important operation that can quickly unify the visual style of the presentation. You can quickly replace the background of your entire presentation by modifying the slide master or using the Format Background feature. In addition, some PPT versions also provide a batch replacement function, which can easily replace the background of all slides. When replacing the background, you should pay attention to choosing a background that matches the theme of the presentation, and ensure that the background clarity and resolution meet the requirements.

Detailed explanation of the method of converting int type to string in PHP Detailed explanation of the method of converting int type to string in PHP Mar 26, 2024 am 11:45 AM

Detailed explanation of the method of converting int type to string in PHP In PHP development, we often encounter the need to convert int type to string type. This conversion can be achieved in a variety of ways. This article will introduce several common methods in detail, with specific code examples to help readers better understand. 1. Use PHP’s built-in function strval(). PHP provides a built-in function strval() that can convert variables of different types into string types. When we need to convert int type to string type,

What is the difference in the 'My Computer' path in Win11? Quick way to find it! What is the difference in the 'My Computer' path in Win11? Quick way to find it! Mar 29, 2024 pm 12:33 PM

What is the difference in the "My Computer" path in Win11? Quick way to find it! As the Windows system is constantly updated, the latest Windows 11 system also brings some new changes and functions. One of the common problems is that users cannot find the path to "My Computer" in Win11 system. This was usually a simple operation in previous Windows systems. This article will introduce how the paths of "My Computer" are different in Win11 system, and how to quickly find them. In Windows1

See all articles