search
HomeWeb Front-endH5 TutorialLearning the basics of canvas

Learning the basics of canvas

Jul 15, 2017 am 11:45 AM
canvasstudy

Canvas (canvas) is a new tag element in html5, used to define graphics, such as charts and other images. The tag is just a container for graphics, and a script (usually javascript) must be used to draw the graphics.

The difference between canvas and svg

##
canvas是HTML5提供的新元素<canvas>,而svg存在的历史要比canvas久远,已经有十几年了。svg并不是html5专有的标签,最初svg是用xml技术(超文本扩展语言,可以自定义标签或属性)描述二维图形的语言。

首先,从它们的功能上来讲,canvas可以看做是一个画布。其绘制出来的图形为标量图,因此,可以在canvas中引入jpg或png这类格式的图片,在实际开发中,大型的网络游戏都是用canvas画布做出来的,并且canvas的技术现在已经相当的成熟。
另外,我们喜欢用canvas来做一些统计用的图表,如柱状图曲线图或饼状图等。而svg,所绘制的图形为矢量图,所以其用法上受到了限制。因为只能绘制矢量图,所以svg中不能引入普通的图片,因为矢量图的不会失真的效果,在项目中我们会用来做一些动态的小图标。
但是由于其本质为矢量图,可以被无限放大而不会失真,这很适合被用来做地图,而百度地图就是用svg技术做出来的。

另外从技术发面来讲canvas里面绘制的图形不能被引擎抓取,如我们要让canvas里面的一个图片跟随鼠标事件:canvas.onmouseover=function(){}。而svg里面的图形可以被引擎抓取,支持事件的绑定。
另外canvas中我们绘制图形通常是通过JavaScript来实现,svg更多的是通过标签来来实现,如在svg中绘制正矩形形就要用<rect>,这里我们不能用属性style="width:XXX;height:XXX;"来定义。
我再来介绍一个svg的js库:TWO.JS。其中包含two.js和three.js前者用于绘制二维图形,后者用于绘制三维图形。TWO.JS可以支持三种格式,svg(默认)、canvas、和WEBGL。当然也可以在普通div中引入。

要从同一图形的一个<canvas>标记中移除元素,需要擦掉重新绘制;而svg很容易编辑,只要从其描述中移除元素即可。

以上是之前在别人博客中看到的,所以先引用过来,待之后熟练掌握canvas,svg再写自己的心得体会。

具体请参考</canvas></rect></canvas>
<br><br><strong><span style="font-family: 'Microsoft YaHei'; font-size: 14px;">1、基本语法</span></strong>
<canvas>您的浏览器不支持canvas</canvas>

当没有设置宽度和高度的时候,canvas会初始化宽度为300px和高度为150px;当浏览器不支持canvas标签的时候,会显示其中的文字。

在canvas坐标体系中,以左上角为坐标原点,向右为x轴正方向,向下为y轴正方向,如下图:

进行绘制需要获取canvas的上下文环境context,之后调用API进行图像绘制

var canvas = document.getElementById("canvasMain"),
    ctx = canvas.getContext("2d");

 替换内容是在不支持标签的浏览器中展示的。也可以通过检测getContext()方法的存在来判断是否支持(有些浏览器会为html规范之外的元素创建默认的html元素对象)

<span style="color: #000000;">var canvas = document.getElementById("canvasMain");
if(canvas.getContext("2d")) {
    var ctx = canvas.getContext("2d");
    // drawing code here
} else {
    // canvas-unsupported code here
}<br></span>

导出在元素上绘制的图像,接收一个参数,即图像的MIME类型格式。若绘制到画布上的图像来自不同域,该方法会报错

var canvas = document.getElementById("canvasMain");if(canvas.getContext) {//取得图像的数据URIvar imgURI = canvas.toDataURL('image/png');//显示图像var image =  document.createElement('img');
    image.src = imgURI;
    document.body.appendChild(image);        
}

2、2D上下文

  • 填充和描边

  填充:用指定的样式(颜色、渐变、图像)填充图形;描边:在图形的边缘画线   两个属性分别是fillStyle  strokeStyle,属性的值可以是字符串、渐变对象或模式对象

  • 绘制矩形

          

  绘制矩形方法:fillRect()  strokeRect()   clearRect()  参数依次为:矩形x坐标、y坐标、宽度、高度

var drawing = document.getElementById('drawing');if(drawing.getContext) {var context = drawing.getContext('2d');
    context.strokeStyle = 'rgba(0, 0, 255, 0.5)';//描边属性context.fillStyle = 'pink';//填充属性context.lineWidth = 3; //描边线条宽度context.lineCap = 'square';//线条末端形状(butt平头、round圆头、square方头)context.lineJoin = 'round';//线条相交的方式(round圆交、bevel斜交、miter斜接)context.fillRect(10, 10, 50, 50);//填充矩形context.fillStyle = 'green';
    context.fillRect(30, 30, 50, 50);
    context.strokeRect(100, 10, 50, 50);//描边矩形context.clearRect(40, 40, 15, 15);//清除画布上的矩形区域             }
  • 绘制路径

   

   closePath()绘制一条连接到路径起点的线条

   fill()填充路径    stroke()描边路径   clip()在路径上创建一个剪切区域

   isPointInPath(x,y)判断画布上的某一点是否位于路径上

var drawing = document.getElementById('drawing');if(drawing.getContext) {/*绘制路径*/var context = drawing.getContext('2d');
            context.strokeStyle = 'pink';
            context.beginPath();//开始绘制新路径//绘制外圆context.arc(100, 100, 99, 0, 2*Math.PI, false);//参数依次为圆心坐标x、y、半径、起始角度(用弧度表示)、结束角度、起始角度是否按逆时针方向计算(flase为顺时针)context.moveTo(194, 100);//将绘图游标移动到(x,y),不画线//绘制内圆context.arc(100, 100, 94, 0, 2*Math.PI, false);//绘制分针context.moveTo(100, 100);
            context.lineTo(100, 25);//从上一点开始绘制一条直线,到(x,y)为止//绘制时针context.moveTo(100, 100);
            context.lineTo(35, 100);//绘制文本context.font = 'bold 14px Arial';//表示文本样式、大小、字体context.textAlign = 'center';//文本对齐方式(start、end、left、right、center),建议用start、end代替left、rightcontext.textBaseline = 'middle';//文本的基线(top、hanging、middle、alphabetical、ideopgraphic、bottom)context.fillText('12', 100, 20);//描边路径            context.stroke();//额外练习context.moveTo(230, 10);//arcTo(x1,y1,x2,y2,radius):从上一点开始绘制一条弧线,到(x2,y2)为止,并以给定的半径穿过(x1,y1)context.arcTo(280, 60, 330, 10, 50);//bezierCurveTo(c1x,c1y,c2x,c2y,x,y):从上一点开始绘制一条曲线,到(x,y)为止,并以(c1x,c1y)(c2x,c2y)为控制点context.bezierCurveTo(210, 70, 290, 90, 300, 100);
            context.moveTo(320, 10);//quadraticCurveTo(cx,cy,x,y):从上一点开始绘制一条二次曲线,到(x,y)为止,并以(cx,cy)为控制点context.quadraticCurveTo(420, 100, 400, 10);//rect(x,y,width,height):从点(x,y)开始绘制矩形,此方法绘制的是矩形路径而不是独立的形状context.rect(450, 10, 50, 50);
            context.stroke();
}
  • 绘制文本

  fillText()绘制文本    strokeText()为文本描边    参数:文本字符串、x坐标、y坐标、可选的最大像素宽度

  • 变换

  

var drawing = document.getElementById('drawing');if(drawing.getContext) {            //变换var context = drawing.getContext('2d');
            context.strokeStyle = 'rgba(0, 0, 255, 0.5)';
            context.beginPath();
            context.arc(100, 100, 99, 0, 2*Math.PI, false);
            context.moveTo(194, 100);
            context.arc(100, 100, 94, 0, 2*Math.PI, false);//变换原点context.translate(100, 100);//将坐标原点移动到该点//旋转表针context.rotate(1);//围绕原点旋转图像angle弧度//绘制分针context.moveTo(0, 0);
            context.lineTo(0, -80);//绘制时针context.moveTo(0, 0);
            context.lineTo(-65, 0);
            context.stroke();

            context.rotate(-1);
            context.fillStyle = 'rgba(0, 0, 255, 0.5)';
            context.save();//保存上下文状态,只保存绘图上下文的设置和变换,不会保存绘图上下文的内容context.fillStyle = 'pink';
            context.translate(-100, -100);
            context.save();
            context.fillStyle = 'green';
            context.fillRect(220, 10, 50, 50);

            context.restore();//返回之前保存的设置context.fillRect(280, 10, 50, 50);

            context.restore();
            context.fillRect(340, 10, 50, 50);
}
  • 绘制图像

   

  drawImage()还可传入元素作为第一个参数,表示把另一个画布内容绘制到当前画布上。

  可能遇到的问题:drawImage()图片不显示在画布上,原因可能是你取图片的时候,此时图片还没有加载出来

window.onload = function(){var drawing = document.getElementById('drawing');if(drawing.getContext) {//图像var context = drawing.getContext('2d');var image = document.images[0];//参数依次表示为:图像元素、源图像x坐标、y坐标、目标的宽度、高度context.drawImage(image, 0, 0, 150, 250);//参数依次表示为:图像元素、源图像x坐标、y坐标、源图像宽度、高度、目标图像x坐标、y坐标、目标图像宽度、高度context.drawImage(image, 100, 300, 500, 600, 0, 0, 70, 80);
        }
};
  • 阴影、渐变、模式

  

   模式与渐变一样,都是从画布原点(0,0)开始的,将填充样式设置为模式对象,只表示在某个特定区域内显示重复的图像,而不是从某个位置开始绘制重复的图像。

   createPattern()第一个参数也可以是

window.onload = function(){var drawing = document.getElementById('drawing');if(drawing.getContext) {//阴影var context = drawing.getContext('2d');
            context.shadowColor = 'rgba(0, 0, 0, 0.5)';//阴影颜色,默认黑色context.shadowOffsetX = 5;//x轴方向的阴影偏移量,默认0context.shadowOffsetY = 5;//y轴方向的阴影偏移量,默认0context.shadowBlur = 4;//模糊的像素数,默认0context.fillStyle = 'rgba(0, 0, 255, 0.5)';
            context.fillRect(10, 10, 50, 50);
            context.fillStyle = 'pink';
            context.fillRect(30, 30, 50, 50);//渐变var gradient = context.createLinearGradient(100, 10, 130, 130);//创建线性渐变,返回CanvasGradient对象的实例。参数:起点x坐标、y坐标、终点x坐标、y坐标gradient.addColorStop(0, 'white');//指定色标,参数:色标位置(0到1之间的数字,0表示开始的颜色,1为结束的颜色)、css颜色值gradient.addColorStop(1, 'black');

            context.fillStyle = gradient;
            context.fillRect(100, 10, 50, 50);var createLinearGradient = function(context, x, y, width, height) {return context.createLinearGradient(x, y, x+width, y+height);
            };var gradientNew = createLinearGradient(context, 180, 10, 50, 50);
            gradientNew.addColorStop(0, 'red');
            gradientNew.addColorStop(1, 'green');
            context.fillStyle = gradientNew;
            context.fillRect(180, 10, 50, 50);var gradientRound = context.createRadialGradient(275, 35, 10, 275, 35, 30);//径向渐变,参数:起点圆的圆心、半径,终点圆的圆心、半径gradientRound.addColorStop(0, 'pink');
            gradientRound.addColorStop(1, 'blue');
            context.fillStyle = gradientRound;
            context.fillRect(250, 10, 50, 50);//模式,即重复的图像,可以用来填充或描边图形var image = document.images[0],
                pattern = context.createPattern(image, 'repeat-x');//创建新模式,参数:图像元素、是否重复(repeat、repeat-x、repeat-y、no-repeat)context.fillStyle = pattern;
            context.fillRect(350, 10, 350, 350);
        }
}
  • Using image data

GetImageData() can obtain the original image data, parameter: x coordinate of the screen area where the data is to be obtained , y coordinate, width, height. The returned object is an instance of ImageData, which has three properties: width, height, and data. Data is an array, which stores the data of each pixel in the image. Each pixel is represented by 4 elements, representing red, green, blue and transparency values ​​respectively. Therefore, the data of the first pixel is saved in the 0th to 3rd elements of the array.

Note: Image data can only be obtained if the canvas is "clean" (that is, the image does not come from other domains).

  • Synthesis

 

globalAlpha: A value between 0 and 1 (inclusive 0 and 1), used to specify transparency, the default is 0.
globalCompositionOperation: Indicates how the graphics drawn later are combined with the graphics drawn first.

 

 

3、WebGL

 

WebGL is for canvas 3D context is not a standard developed by W3C.

Canvas is an important new feature of H5, and everyone needs to spend some effort to learn and use it.

The above is the detailed content of Learning the basics of canvas. For more information, please follow other related articles on the PHP Chinese website!

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
Mastering Microdata: A Step-by-Step Guide for HTML5Mastering Microdata: A Step-by-Step Guide for HTML5May 14, 2025 am 12:07 AM

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

What's New in HTML5 Forms? Exploring the New Input TypesWhat's New in HTML5 Forms? Exploring the New Input TypesMay 13, 2025 pm 03:45 PM

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

Understanding H5: The Meaning and SignificanceUnderstanding H5: The Meaning and SignificanceMay 11, 2025 am 12:19 AM

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

H5: Accessibility and Web Standards ComplianceH5: Accessibility and Web Standards ComplianceMay 10, 2025 am 12:21 AM

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

What is the H5 tag in HTML?What is the H5 tag in HTML?May 09, 2025 am 12:11 AM

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.