Only with a strong foundation in drawing, coloring, and transforming basic two-dimensional graphics can we use Canvas more effectively;
Below, I will briefly understand how canvas draws basic shapes (rectangle, straight line, arc, Bezier curve), etc.;
First post all the following related The basic code segment to implement operation:
Base code <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script type="text/javascript" src="modernizr-latest.js"></script> <script type="text/javascript"> window.addEventListener("load", eventWindowLoaded, false); var Debugger = function() {}; Debugger.log = function(message) { try { console.log(message); } catch (exception) { return; } } function eventWindowLoaded() { canvasApp(); } function canvasSupport() { return Modernizr.canvas; } function canvasApp() { //是否支持CANVAS判断 if(!canvasSupport()) { return; } //取Canvas var theCanvas = document.getElementById("canvasOne"); //获取绘图环境context var context = theCanvas.getContext("2d"); //绘图方法的实现 function drawScreen() {} //绘图方法调用执行 drawScreen(); } </script> </head> <body> <div style="position: absolute; top: 50px; left: 50px; border:1px solid #0000ff"> <canvas id="canvasOne" width="550" height="400"> Your browser does not support HTML5 Canvas. </canvas> </div> </body> </html>
For all the following example codes, just replace the above function drawScreen()!
Basic Rectangle Shape (rectangle)
In Canvas, there are three ways to draw a rectangle: filling (), stroking(), or clearing
The three methods correspond to the following three methods (the parameters are all the same, which are the coordinates [x, y] of the upper left corner of the rectangle, the Width, height of rectangle):
#fillRect(x,y,width,height): fill the rectangular area;
- ##strokeRect(x,y,width,height): draw A rectangular border;
Example function drawScreen() { context.fillStyle = '#000000';//填充颜色 context.strokeStyle = '#00ff00';//轮廓颜色 context.lineWidth = 2;//线宽 context.fillRect(10, 10, 40, 40);//填充矩形 context.strokeRect(7, 7, 46, 46);//画矩形轮廓 context.clearRect(20, 20, 20, 20);//清除矩形区域 }上一篇有提到Current state; 当我们在绘画时,我们可以利用所谓的绘画状态的堆栈, 对于canvas context在任何一个时间的数据的每一个状态都会存储; 下面是对于每一个状态,存储在堆栈中的一个数据列表; 变换矩阵(旋转、移动、缩放等); 剪切区域; Canvas特征的当前值(部分): — globalAlpha — globalCompositeOperation — strokeStyle — textAlign, textBaseline — lineCap, lineJoin, lineWidth, miterLimit — fillStyle — font — shadowBlur, shadowColor, shadowOffsetX, and shadowOffsetY 在绘图环境中,正在操作的当前path and 当前位置并不是状态的一部分;Importmant!!! 如何保存恢复当前的状态呢? context.save()---push to stack; context.restore()---pop form stack; 先有一个简单的印象,之后会更加详细的剖析;
Create Lines(直线)
利用path来创建线(line)
Path:用来画出一系列的相连的圆弧或者线条,可以称之为“轨迹”,使用它可以画出任意复杂的形状;
一个Canvas Context仅有一个current path ;
在调用context.save()时,current path并不做为当前的状态(current state)存储于stack中;
利用.beginPath()功能方法来启动一个Path;
利用.closePath()功能方法来关闭一个Path;
Example:画一条10px宽度的水平直线 function drawScreen() { context.strokeStyle = "#000000";//线的颜色 context.lineWidth = 10;//线的宽度 context.beginPath();//启动path context.moveTo(20, 20); context.lineTo(100, 20); context.stroke();//绘画 context.closePath();//关闭path }
线的属性:lineCap
直线lineCap属性:线帽,也就是线两端的样式,只有绘制较宽的线的,它才有效;
有三个有效值:butt\round\square
"butt":默认值,指定了线段应该没有线帽。
"round":线段应该带有一个半圆形的线帽,半圆的直径等于线段的宽度,并且线段在端点之外扩展了线段宽度的一半。
"square":线段应该带有一个矩形线帽。这个值和 "butt" 一样,但是线段扩展了自己的宽度的一半。
Example function drawScreen() { context.strokeStyle = "#000000";//线的颜色 context.lineWidth = 10;//线的宽度 context.lineCap="butt";//butt\round\square context.beginPath();//启动path context.moveTo(20, 20); context.lineTo(100, 20); context.stroke();//绘画 context.closePath();//关闭path context.lineCap="round";//butt\round\square context.beginPath();//启动path context.moveTo(20, 40); context.lineTo(100, 40); context.stroke();//绘画 context.closePath();//关闭path context.lineCap="square";//butt\round\square context.beginPath();//启动path context.moveTo(20, 60); context.lineTo(100, 60); context.stroke();//绘画 context.closePath();//关闭path }
线的属性:lineJoin
lineJoin属性:表示两条线段如何连接;
当一个路径包含了线段或曲线相交的交点的时候,用lineJoin 属性来说明如何绘制这些交点;
该属性也有三个有效值:miter bevel round
"miter":默认值,两条线段的外边缘一直扩展到它们相交
"bevel":以一个斜边进行连接
"round":以一个圆弧边进行连接
function drawScreen() { context.strokeStyle = "#000000"; context.lineWidth = 10; context.lineJoin = "miter"; context.beginPath(); context.moveTo(20, 20); context.lineTo(100, 20); context.lineTo(100, 40); context.stroke(); context.closePath(); context.lineJoin = "bevel"; context.beginPath(); context.moveTo(20, 60); context.lineTo(100, 60); context.lineTo(100, 80); context.stroke(); context.closePath(); context.lineJoin = "round"; context.beginPath(); context.moveTo(20, 100); context.lineTo(100, 100); context.lineTo(100, 120); context.stroke(); context.closePath(); context.lineJoin = "miter"; context.beginPath(); context.moveTo(20, 140); context.lineTo(100, 140); context.lineTo(80, 180); context.stroke(); context.closePath(); }
Arcs(圆弧)
一段圆弧可以是一个完整的圆也可以圆的一部分;
生成圆弧:context.arc()
context.arc(x, y, radius, startAngle, endAngle, anticlockwise)
参数依次代表圆心,半径、起始角度、终止角度、圆弧的方向; 角度都是以弧度来表示;
anticlockwise为布尔类型 ;true为顺时针、false为逆时针
function drawScreen() { context.strokeStyle = "black"; context.lineWidth = 5; context.beginPath(); context.arc(100, 100, 20, (Math.PI / 180) * 0, (Math.PI / 180) * 360, false); context.stroke(); context.closePath(); context.beginPath(); context.arc(100, 200, 20, (Math.PI / 180) * 0, (Math.PI / 180) * 90, false); context.stroke(); context.closePath(); context.beginPath(); context.arc(100, 300, 20, (Math.PI / 180) * 0, (Math.PI / 180) * 90, true); context.stroke(); context.closePath(); }
Bezier Curves(贝赛尔曲线)
Canvas支持二次 and 三次贝塞尔曲线的绘画
此处的贝塞尔曲线是定义在二维空间里的,需要一个起始点、一个终止点,再加上一个或者两个控制点来创建曲线;
控制点来决定所构造曲线的走向;
三次贝塞尔曲线需要两个点;
二次贝塞尔曲线需要一个点即可;
主要通过以下两个方法来绘画:
context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
context.quadraticCurveTo(cpx, cpy, x, y)
二次贝塞尔曲线: function drawScreen() { context.strokeStyle = "black"; context.lineWidth = 5; context.beginPath(); context.moveTo(0, 0); context.quadraticCurveTo(500, 25, 0, 100); context.stroke(); context.closePath(); } 曲线的起始点为(0,0),结束点为(0,100) 点(500,25)控制最终生成曲线的走向; 三次贝塞尔曲线: function drawScreen() { context.strokeStyle = "black"; context.lineWidth = 5; context.beginPath(); context.moveTo(0, 0); context.bezierCurveTo(0, 125, 300, 175, 150, 300); context.stroke(); context.closePath(); } 曲线的起点(0,0),结束点(150,300) (0, 125), (300, 175)这两个为控制点; 大家可能自己运行一下代码,看看效果,此处就不贴图了。。
The above is the detailed content of Detailed explanation of the sample code of html5 Canvas drawing (1). For more information, please follow other related articles on the PHP Chinese website!

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.

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo


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.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools