This article explains in detail how to use HTML5 Canvas drawing for reference and learning by PHP Chinese netizens
First of all, please note: <canvas>## The # element is not supported by some older browsers, but is supported by Firefox 1.5+, Opera 9+, newer versions of Safari, Chrome, and Internet Explorer 9. </canvas>
requires first Obtain the 2D rendering context to draw the
Canvas draws images based on state. <span style="font-family: verdana, Arial, Helvetica, sans-serif;"></span>
1. Use the following two methods to define a path
context.moveTo(x,y); //起点context.lineTo(x,y); //连线到终点
2. For multiple Paths, if you want to process them separately, you need to add the following two methods at the beginning and end of the path definition to separate them
context.beginPath(); context.closePath();
3. Path style
context.lineWidth //定义线条宽度context.strokeStyle //定义线条颜色context.fillStyle //填充颜色context.stroke(); //绘制线条context.fill(); //绘制填充的颜色块
4. Draw an arc
context.arc( centerx, centery, radius, //圆心坐标(x,y)以及半径r startingAngle, endingAngle, //开始的弧度值,和结束的弧度值 anticlockwise = false //可选参数,(false顺时针绘制)还是(true逆时针绘制))
5. Draw a rectangle
context.rect(x, y, width, height); //设置矩形状态context.fill(); context.stroke();//或者context.fillRect(x, y, width, height); //绘制填充的矩形context.strokeRect(x, y, width, height); //绘制边框的矩形
6.Format of attribute values of fillStyle and strokeStyle
#FFF #333rgb(255,128,0) rgba(100,100,100,0.8) hsl(20,62%,28%) hsla(40,83%,33%,0.6) red
7. Line Cap: lineCap is used to set the shape of both ends of the line. It has the following three values:
butt(default) //默认缺省round //圆头square //方头context.lineCap = "round";
8. The shape of intersection between lines: lineJoin Three attribute values:
miter(default) //尖角bevel //斜接round //圆角context.lineJoin = "round";//当尖角很尖锐时,会出现lineJoin为bevel//此时跟另外一个属性有关:miterLimit,默认值是10//当在lineJoin为miter情况下,miterLimit大于10时,lineJoin会自动变成bevel
9. Image transformation and state savingImage transformation:
位移:translate(x,y); 旋转:rotate(deg); 缩放:scale(sx,sy);//保存当前图形状态:context.save();//恢复图形的所有状态:context.restore();//使用:context.save(); context.translate(x,y); context.restore();
10. Transformation matrix
a c e b d f0 0 1a水平缩放(1) b水平倾斜(0) c垂直倾斜(0) d垂直缩放(1) e水平位移(0) f垂直位移(0) 即:默认时,该变换矩阵为单位阵//设置变换矩阵transform(a,b,c,d,e,f);//重置变换矩阵setTransform(a,b,c,d,e,f);
11. Linear gradient
var grd = context.createLinearGradient(xstart,ystart,xend,yend);//开始坐标到结束坐标grd.addColorStop(stop,color);//stop为浮点数,开始坐标点到结束坐标点直线上,某个位置(0.0~1.0之间)//例:var skyStyle = context.createLinearGradient(0,0,800,800); skyStyle.addColorStop(0.0, 'black'); skyStyle.addColorStop(1.0, 'blue'); context.fillStyle = skyStyle;
12. Radial gradient
var grd = context.createRadialGradient(x0,y0,r0,x1,y1,r1);//开始圆心坐标到结束圆心坐标,以及半径grd.addColorStop(stop,color);//stop为浮点数,开始坐标点到结束坐标点直线上,某个位置(0.0~1.0之间)
13. Image filling
createPattern(img,repeat-style) //img为图片对象,repeat-style填充格式//其中repeat-style: no-repeat/repeat-x/repeat-y/repeat//例:var backgroundImage = new Image(); backgroundImage.src = "bg.jpg"; backgroundImage.onload = function(){var pattern = context.createPattern(backgroundImage,"repeat"); context.fillStyle = pattern; context.fillRect(0,0,800,800); }
14.Canvas filling
createPattern(canvas,repeat-style) //canvas对象,repeat-style填充格式
Example:
window.onload=function(){ var canvas=document.getElementById("canvas"); canvas.width=800; canvas.height=800; var context=canvas.getContext("2d"); var backCanvas=createBackgroundCanvas(); var pattern=context.createPattern(backCanvas,"repeat"); context.fillStyle=pattern; context.fillRect(0,0,800,800); } function createBackgroundCanvas(){ var backCanvas=document.createElement("canvas"); backCanvas.width=100; backCanvas.height=100; var backContext=backCanvas.getContext("2d"); backContext.beginPath(); backContext.moveTo(15,15); backContext.lineTo(50,50); backContext.lineWidth=10; backContext.strokeStyle="green"; backContext.stroke(); return backCanvas; }
15.video filling
createPattern(video,repeat-style) //video视频对象
16. Another arc drawing method
context.arcTo( x1,y1,x2,y2, //x1,y1,x2,y2两个坐标与起始点x0,y0组成一个角 radius //半径)
Example:
context.moveTo(x0,y0); context.arcTo(x1,y1,x2,y2,R);//起始点为(x0,y0),该弧线与01线以及12线相切
17. Bezier CurveBezier Quadratic Curve
context.moveTo(x0, y0); //起始点context.quadraticCurveTo( x1, y1, //控制点坐标 x2, y2 //终点坐标)Bezier Cubic Curve
context.moveTo(x0, y0); //起始点context.bezierCurveTo( x1, y1, //控制点坐标 x2, y2, //控制点坐标 x3, y3 //终点坐标)
18. Text rendering
context.font = "font-style font-variant font-weight font-size font-family"; //css字体样式,默认值:"20px sans-serif"context.fillText(String, x, y, [maxlen]); //String字符串,和坐标位置,第四个为可选参数,这行文字的最长宽度context.strokeText(String, x, y, [maxlen]); font-style: normal (Default) italics (斜体字) oblique (倾斜字体) font-variant: normal (Default) small-caps (小写英文字母变成小的大写字母) font-weight: normal (Default) lighter bold bolder 100,200,300,400(normal) 500,600,700(bold) 800,900font-size: 20px (Default) 2em 150%font-family: 设置多种字体备选,支持@font-faceText horizontal alignment:
context.textAlign = left right centerVertical alignment of text:
context.textBaseline = top middle bottom alphabetic (Default) ideographic hanging
Metrics of text:
context.measureText(String).width //获取渲染的字符串的宽度
19. Shadow
context.shadowColor //阴影颜色context.shadowOffsetX //阴影的位移值context.shadowOffsetY context.shadowBlur //阴影模糊度
20. Global method:
context.globalAlpha = 1 (Default) //全局透明度,默认不透明context.globalCompositeOperation = "source-over" (Default) //绘制的图像在重叠的时候的效果,默认是(source-over)后面绘制的图像覆盖前面绘制的图像"source-atop" //后面绘制的图像覆盖前面绘制的图像,但后面的图像只显示重叠部分"source-in" //后面绘制的图像覆盖前面绘制的图像,但只显示重叠部分"source-out" //只显示后绘制的图像,而且重叠部分被切掉"destination-over" //前面绘制的图像覆盖后面绘制的图像"destination-atop" //前面绘制的图像覆盖后面绘制的图像,但前绘制的图像只显示重叠部分"destination-in" //前面绘制的图像覆盖后面绘制的图像,但只显示重叠部分"destination-out" //只显示前绘制的图像,而且重叠部分被切掉"lighter" //重叠部分颜色叠加融合"copy" //只显示后绘制图像"xor" //异或,重叠部分被挖空
21. Clip area Method to set the currently created path as the current clipping path
void ctx.clip();void ctx.clip(fillRule);void ctx.clip(path, fillRule);
fillRule
This algorithm determines whether a point is within the path or within outside the path. pathThe Path2D path that needs to be cut.
ctx.arc(100, 100, 75, 0, Math.PI*2, false); ctx.clip(); ctx.fillRect(0, 0, 100,100);
22. Non-zero wrapping principle Path direction
Application: Hollow paper-cut effect
23.canvas interaction
context.clearRect(x,y,width,height) //清空指定的区域context.isPointInPath(x,y) //点击检测函数,该点是否在当前规划路径内,当检测点包含在当前或指定的路径内,返回 true;否则返回 false//以下两个是获取鼠标点击在canvas坐标var x = event.clientX - canvas.getBoundingClientRect().left;var y = event.clientY - canvas.getBoundingClientRect().top;
24. Extend the context of CanvasExtend the drawStar method to context:
CanvasRenderingContext2D.prototype.drawStar = function(){}
25.Canvas compatibility Detection
<canvas>当前浏览器不支持Canvas,请更换浏览器再试</canvas>
Compatibility issues between Canvas and IE6, 7, and 8 browsers
Introducing the explorecanvas library:https://code.google.com/p/explorecanvas/<!--[if IE]><script type="text/javascript" src="../excanvas.js"></script><![endif]-->
26. canvas graphics library: canvasplus || artisanJS || RGraph
code.google.com/p/canvasplusartisanjs.comroopons.com. au/wp-content/plugins/viral-optins/js/rgraph27. Canvas API interface document:
developer.mozilla.org/zh-CN /docs/Web/API/CanvasRenderingContext2DThe above is the detailed content of HTML5 Canvas drawing example tutorial. For more information, please follow other related articles on the PHP Chinese website!

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 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.

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 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.

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.

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools