search
HomeWeb Front-endH5 TutorialDetailed explanation of html5 canvas common API summary (2)--Drawing API

Canvas can draw many wonderful styles and beautiful effects. Through a few simple APIs, you can present ever-changing effects on the canvas. You can also create web games. Next, I will summarize the APIs related to drawing.

When painting, canvas is equivalent to the canvas, and context is equivalent to the brush.

1. Draw lines

moveTo(x0,y0): Move the current brush (ictx) to the position (x0,y0).

lineTo(x1,y1): Draw a straight line from the current position (x0, y0) to (x1, y1).

beginPath(): Open a path or reset the current path.

closePath(): Return to the starting point of the path from the current point, which is the position, avoidance and path of the previous beginPath.

stroke(): draw. This function must be added to draw the picture, so this must be placed at the end.

var icanvas=document.getElementById("iCanvas");

var ictx=icanvas.getContext("2d");

ictx.beginPath();

ictx.moveTo(0,0);

ictx.lineTo(300,150);

ictx.lineTo(3,150);

ictx.closePath();

ictx.stroke();



Effect:

Detailed explanation of html5 canvas common API summary (2)--Drawing API

It should be noted here that if closepath is placed after the stroke function, it will not It will be drawn as a closed line, because it has been drawn before closing, so the straight line on the left will not be drawn.

2. Line style

lineCap: line endpoint style, butt, round, square.                                             

Detailed explanation of html5 canvas common API summary (2)--Drawing API

#lineJoin: The inflection point style when two lines intersect. When set to miter, you can also set the maximum length of the inflection point junction through miterLimet.     

Detailed explanation of html5 canvas common API summary (2)--Drawing API

miterLimet: If the miter length exceeds the value of miterLimit, the corners will be displayed with the "bevel" type of lineJoin.

lineWidth: line width

strokeStyle: line color, gradient (defined gradient object), mode. context.strokeStyle="#333";

var iCanvas=document.getElementById("iCanvas");

var ictx=iCanvas.getContext("2d");

ictx.beginPath();

ictx.strokeStyle="#0000ff";

ictx.lineWidth=20;

ictx.lineCap="round";

ictx.moveTo(10,10);

ictx.lineTo(80,80);

ictx.stroke();

ictx.beginPath();//在这里必须beginPath,不然一直会以第一个为基础会话,在最后的stroke的时候,会再次画一条黑色的斜线,一共3条线。

ictx.strokeStyle="#000000";

ictx.lineCap="butt";

ictx.lineWidth=10;

ictx.moveTo(80,10);

ictx.lineTo(10,80);

ictx.stroke();



beginPath and closePath can appear unpaired. There is almost no relationship between the two. closePath is used to close the end point. Draw a closed path with the starting point.

3. Draw a curve

arc(x,y,radius,startAngle,endAngle,anticlockwise): draw a curve, radius is the radius of the curve, startAngle, endAngle starting angle and the end angle, using radians (Math.PI/180)*angle value, anticlockwise drawing direction;

arcTo(x1,y1,x2,y2,radius): Draw the curve before the two tangent lines.

ictx.beginPath();

ictx.moveTo(20,20);           // 创建开始点

ictx.lineTo(100,20);          // 创建水平线

ictx.arcTo(150,20,150,70,50); // 创建弧

ictx.lineTo(150,120);         // 创建垂直线

ictx.stroke();



The starting point of the drawn curve and the end point of the horizontal line are tangent to the line connecting the first set point, and the end point of the curve and the first set point are tangent to The line connecting the second set point is tangent.

Detailed explanation of html5 canvas common API summary (2)--Drawing API

quadraticCurveTo(x1,y1,x2,y2): quadratic Bezier curve. (x1, y1) The coordinates of the control point, (x2, y2) the coordinates of the end point

bezierCurveTo(x1,y1,x2,y2,x,y): cubic Bezier curve. (x1, y1) The coordinates of control point 1, (x2, y2) The coordinates of control point 2 (x, y) The coordinates of the end point.

Bezier curves are very useful when drawing some very smooth curves.

4. Draw rectangle and fill

rect(): Create a rectangle;

fillRect(x,y,width,height): Draw the rectangle Filled rectangle: (x, y) starting point, width, height Rectangle width and height

strokeRect(): Draw a rectangular wireframe

clearRect(): Clear the rectangle.

ictx.fillStyle="#0000ff";//设定填充颜色

ictx.fillRect(20,20,150,100);

ictx.strokeRect(180,20,100,100);



5. Brush attributes

fillStyle: Set the fill color, gradient or pattern (patten);

strokeStyle: Brush color, gradient or pattern

6. Draw shadow

shadowColor: Shadow yanse

shadowBlur: Blur level

shadowOffsetX: The horizontal distance of the shadow

shadowOffsetY: The vertical distance of the shadow

ictx.shadowBlur=20;

ictx.shadowColor="#456";

ictx.shadowOffsetX=-10;

ictx.shadowOffsetY=30;//先设置阴影再画矩形

ictx.fillStyle="#108997";

ictx.fillRect(20,20,100,80);

ictx.stroke();



Detailed explanation of html5 canvas common API summary (2)--Drawing API

7. Draw gradient

createLinearGradient(x1,y1,x2,y2): Draw a linear gradient, (x1,y1) is the starting point of the gradient, (x2,y2) is Depending on the end point and position of the gradient, a vertical or horizontal gradient can be created.

createRadialGradient(x1,y1,r1,x2,y2,r2): Radial gradient: (x1,y1) is the starting point center of the gradient, r1 is the radius, (x2,y2) is the gradient End point, r2 is the end point radius;

Both gradients need to use

addColorStop(stop,color) to set the gradient process, stop is a value from 0.0 to 1.0.

var grd=ictx.createLinearGradient(0,0,170,0);

grd.addColorStop(0,"#000");

grd.addColorStop(0.5,"#378923");

grd.addColorStop(1,"#ddd");

ictx.fillStyle=grd;//这里渐变是一个对象,用来向fillstyle传值

ictx.fillRect(20,20,150,100);

 

var grd=ictx.createRadialGradient(300,225,15,250,225,100);

grd.addColorStop(0,"#345");

grd.addColorStop(1,"#fff");

ictx.fillStyle=grd;

ictx.fillRect(200,150,150,100);



Detailed explanation of html5 canvas common API summary (2)--Drawing API

8.填充背景

createPattern(image,"repeat|repeat-x|repeat-y|no-repeat"):image是一个图片对象,后面的参数是用来设定图片的重复方式。

9.其他相关API

fill():填充当前路径。

isPointInPath():ictx.isPointInPath(x,y);判断这个点是否位于当前路径

清除画布方法:获取画布的宽高,icanvas.height,icanvas.width;然后使用clearRect();

修改画布的宽高:icanvas.width='200';icanvas.width='300'的方法。

globalAlpha:设置透明度,只能是0~1的数字,如果透明度不一样,在画第二幅之前重新设置即可。

toDataURL:icanvas.toDataURL(type,encoderOptions),这个函数返回一个image的base64的URI,参数都是可选的,type可以设置图片类型如image/jpeg,image/webp,默认是image/png;encoderOptions是一个0~1的数字,用来设置image/jpeg,image/webp的图片质量,其他格式的type设置这个参数无效。

10.剪裁

clip():从画布中剪裁任意形状和尺寸的画布,之后所有的绘图都会被限制在剪裁的区域内。这个方法通常和绘制矩形,圆形等路径一起使用,在这些方法后面,剪切这个图像,后来画的就必须在这个剪切后的画布上了。

ictx.arc(100,100,50,(Math.PI/180)*0,(Math.PI/180)*360,true);

ictx.stroke();

ictx.clip();

ictx.fillStyle="green";

ictx.fillRect(0,0,150,100);



Detailed explanation of html5 canvas common API summary (2)--Drawing API

如果还想操作外部的画布,在剪切前使用save()函数保存,剪切后使用restore()函数恢复到之前保存的状态,但是中间做的操作不会消失哈。

以上就是详解html5 canvas常用api总结(二)--绘图API 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

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
H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

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: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

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.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

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: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

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.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

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.

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

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

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.