html2canvas教程
Interested in CSS animation? Check out Creating Animations with CSS, a complete course on CSS Transitions and Keyframes animation by expert web developer Donovan Hutchinson, available for SitePoint members. For a sample of HTML5 canvas animations, watch Illustrations with the HTML5 Canvas below, it’s one video in our Start Animating with the HTML5 Canvas mini course.
对CSS动画感兴趣? 查阅由Web开发专家Donovan Hutchinson提供的有关使用CSS创建动画的完整教程,有关CSS过渡和关键帧动画,适用于SitePoint成员。 有关HTML5画布动画的示例,请观看下面HTML5 Canvas插图,这是我们HTML5 Canvas mini 动画入门课程中的一个视频。
One of the most important instruments in a painter’s toolkit is their canvas. It gives them the freedom to express all kinds of feelings, impressions, ideas, and so forth, in almost unlimited variations and combinations. And that freedom can be restricted only by two things — their skill level and their imagination.
画家工具包中最重要的工具之一就是画布。 它使他们可以自由地以几乎无限的变化和组合来表达各种感觉,印象,想法等。 而自由只能受到两方面的限制-他们的技能水平和想象力。
The situation in the web development world is similar. With the ongoing progress of HTML5 and its powerful specifications, web developers have gained the ability to do things that were impossible in the past. Drawing graphics and creating animations directly in the browser is now completely possible thanks to a technology called HTML5 Canvas.
Web开发领域的情况与此类似。 随着HTML5及其功能强大的规范的不断发展,Web开发人员已具备执行过去无法完成的工作的能力。 借助HTML5 Canvas技术,现在完全可以在浏览器中直接绘制图形和创建动画。
什么是HTML5 Canvas? (What is HTML5 Canvas?)
The canvas element is an element defined in HTML code using width
and height
attributes. The real power of the canvas element, however, is accomplished by taking advantage of the HTML5 Canvas API. This API is used by writing JavaScript that can access the canvas area through a full set of drawing functions, thus allowing for dynamically generated graphics.
canvas元素是HTML代码中使用width
和height
属性定义的元素。 但是,canvas元素的真正功能是通过利用HTML5 Canvas API来实现的。 通过编写JavaScript可以使用此API,该JavaScript可以通过全套绘图功能访问画布区域,从而可以动态生成图形。
HTML5 Canvas有何优点? (What’s so Great About HTML5 Canvas?)
Here are some reasons you might want to consider learning to use HTML5’s canvas feature:
您可能需要考虑学习使用HTML5的画布功能的一些原因:
Interactivity. Canvas is fully interactive. It can respond to a user’s actions by listening for keyboard, mouse, or touch events. So a developer is not restricted to only static graphics and images.
互动性。 画布是完全交互式的。 它可以通过侦听键盘,鼠标或触摸事件来响应用户的操作。 因此,开发人员不仅限于静态图形和图像。
Animation. Every object drawn on the canvas can be animated. This allows for all levels of animations to be created, from simple bouncing balls to complex forward and inverse kinematics.
动画。 画布上绘制的每个对象都可以设置动画。 从简单的弹跳球到复杂的正反运动学 ,这都可以创建所有级别的动画。
Flexibility. Developers can create just about anything using canvas. It can display lines, shapes, text, images, etc. — with or without animation. Plus, adding video and/or audio to a canvas application is also possible.
灵活性。 开发人员可以使用画布创建几乎所有内容。 它可以显示线条,形状,文本,图像等,带有或不带有动画。 另外,还可以将视频和/或音频添加到画布应用程序。
Browser/Platform Support. HTML5 Canvas is supported by all major browsers and can be accessed on a wide range of devices including desktops, tablets, and smart phones.
浏览器/平台支持。 所有主流浏览器都支持HTML5 Canvas,并且可以在包括台式机,平板电脑和智能手机在内的各种设备上进行访问。
Popularity. Canvas popularity is rapidly and steadily growing so there is no shortage of resources available.
人气。 画布的受欢迎程度正在Swift而稳定地增长,因此不乏可用资源。
It’s a web standard. Unlike Flash and Silverlight, Canvas is open technology that’s part of HTML5. And although not all of its features are implemented in all browsers, developers can be certain canvas will be around indefinitely.
这是一个网络标准。 与Flash和Silverlight不同,Canvas是HTML5的一部分的开放技术。 尽管不是所有浏览器都实现了所有功能,但是开发人员可以确定canvas会无限期地存在。
Develop once, run everywhere. HTML5 Canvas offers great portability. Once created, Unlike Flash and Silverlight, a canvas application can run almost anywhere — from the largest computers to the smallest mobile devices.
一次开发,随处可见。 HTML5 Canvas提供了很好的可移植性。 创建后,与Flash和Silverlight不同,画布应用程序几乎可以在任何地方运行-从最大的计算机到最小的移动设备。
Free and accessible development tools. The basic tools for creating HTML5 canvas applications are just a browser and a good code editor. Plus, there are many great and free libraries and tools to help developers with advanced canvas development.
免费和可访问的开发工具。 创建HTML5 canvas应用程序的基本工具只是浏览器和良好的代码编辑器。 此外,还有许多出色的免费库和工具可帮助开发人员进行高级画布开发。
您可以使用HTML5 Canvas创建哪些应用程序? (What Applications Can You Create with HTML5 Canvas?)
OK, canvas is great. But what exactly can use it for? Let’s see.
好,帆布很棒。 但是它到底能用来做什么呢? 让我们来看看。
Gaming. The HTML5 Canvas’ feature set is an ideal candidate for producing all sorts of 2D and 3D games.
赌博。 HTML5 Canvas的功能集是制作各种2D和3D游戏的理想选择。
Advertising. HTML5 Canvas is a great replacement for Flash-based banners and ads. It has all the needed features for attracting buyers’ attention.
广告。 HTML5 Canvas可以很好地替代基于Flash的横幅和广告。 它具有吸引买家注意力的所有必要功能。
Data Representation. HTML5 can collect data from global data sources and use it to generate visually appealing and interactive graphs and charts with the canvas element.
数据表示。 HTML5可以从全局数据源收集数据,并使用它来生成具有canvas元素的视觉吸引力和交互式图形和图表。
Education and Training. HTML5 canvas can be used to produce effective and attractive learning experiences, combining text, images, videos, and audio.
教育和培训。 HTML5 canvas可以用于结合文本,图像,视频和音频来产生有效且有吸引力的学习体验。
Art and Decoration. With a little bit of imagination and canvas’s wide variety of colors, gradients, patterns, transparency, shadows, and clipping features, all kinds of artistic and decorative graphics can be drawn.
艺术和装饰。 借助一点点的想象力和画布的各种颜色,渐变,图案,透明度,阴影和剪切功能,可以绘制各种艺术和装饰性图形。
Now that we know why we should learn canvas, let’s look at the basics of HTML5 Canvas and how to start using it.
现在我们知道了为什么我们应该学习画布,让我们看看HTML5 Canvas的基础知识以及如何开始使用它。
画布渲染上下文 (Canvas Rendering Contexts)
Every HTML5 canvas element must have a context. The context defines what HTML5 Canvas API you’ll be using. The 2d context is used for drawing 2D graphics and manipulating bitmap images. The 3d context is used for 3D graphics creation and manipulation. The latter is actually called WebGL and it’s based on OpenGL ES.
每个HTML5 canvas元素都必须具有一个上下文 。 上下文定义了您将使用HTML5 Canvas API。 2d上下文用于绘制2D图形和处理位图图像。 3d上下文用于3D图形创建和操作。 后者实际上称为WebGL ,它基于OpenGL ES 。
入门 (Getting Started)
To get started with canvas, all you need is a code editor and a browser with HTML5 canvas support. I use Sublime Text and Google Chrome, but you can use whatever you want.
要开始使用画布,您只需要一个代码编辑器和一个支持HTML5画布的浏览器。 我使用Sublime Text和Google Chrome,但是您可以随意使用。
Our HTML to start will look like this:
我们开始HTML将如下所示:
<canvas id="exampleCanvas" width="500" height="300">
<!-- OPTION 1: leave a message here if browser doesn't support canvas -->
<p>Your browser doesn’t currently support HTML5 Canvas.
Please check caniuse.com/#feat=canvas for information on
browser support for canvas.</p>
<!-- OPTION 2: put fallback content (text, image, Flash, etc.)
if the browser doesn't support canvas -->
</canvas>
And here is our JavaScript, which we can include at the bottom of our HTML page:
这是我们JavaScript,可以将其包含在HTML页面的底部:
var canvas = document.getElementById('exampleCanvas'),
context = canvas.getContext('2d');
// code examples will continue here...
By default, the browser creates canvas elements with a width of 300 pixels and a height of 150 pixels, even if these aren’t specified in the HTML. You can change the size by specifying the width
and height
, as I’ve done in the HTML.
默认情况下,即使未在HTML中指定,浏览器也会创建宽度为300像素,高度为150像素的canvas元素。 您可以通过指定width
和height
来更改大小,就像我在HTML中所做的那样。
Notice also that we’ve given the canvas an id
attribute that we’ll use in our JavaScript. And finally, if you want, you can use CSS to add a border to make the canvas visible by means of a thin frame. This is not required, it’s used as a visual aid for us to see the boundary of the canvas element.
还要注意,我们给了画布一个id
属性,该属性将在JavaScript中使用。 最后,如果需要,可以使用CSS添加边框以使画布通过细框架可见。 这不是必需的,它用作我们查看画布元素边界的视觉辅助。
Notice that between the opening and closing <canvas>
tags, I’ve added content that will be displayed if the browser doesn’t support canvas. This can be just about any type of content that an older browser supports.
注意,在开始和结束<canvas>
标记之间,我添加了如果浏览器不支持canvas时将显示的内容。 这几乎可以是旧版浏览器支持的任何类型的内容。
The JavaScript starts with two lines. In the first line we create a variable that caches our canvas element via its ID. The second line creates a variable (context
) that references the 2D context for the canvas using the getContext()
function. We’ll use the context
variable to access all canvas drawing functions and properties.
JavaScript以两行开头。 在第一行中,我们创建一个变量,该变量通过其ID缓存画布元素。 第二行创建一个变量( context
),该变量使用getContext()
函数引用画布的2D上下文。 我们将使用context
变量访问所有画布绘制功能和属性。
With our canvas ready to go we can start experimenting with the Canvas API. But before that, let’s clarify a few more aspects of the canvas feature.
准备好画布后,我们就可以开始尝试Canvas API了。 但是在此之前,让我们澄清一下画布功能的其他方面。
HTML5画布元素大小与绘图表面大小 (HTML5 Canvas Element Size vs. Drawing Surface Size)
Besides the canvas element’s width
and height
attributes, you can also use CSS to set the size of a canvas element. However, sizing a canvas element with CSS is not the same as setting the element’s width
and height
attributes. This is because a canvas actually has two sizes: the size of the element itself and the size of the element’s drawing surface.
除了canvas元素的width
和height
属性,您还可以使用CSS设置canvas元素的大小。 但是,使用CSS调整画布元素的大小与设置元素的width
和height
属性是不同的。 这是因为画布实际上具有两种尺寸:元素本身的尺寸和元素绘图表面的尺寸。
When you set the element’s width
and height
attributes, you set both the element’s size and the size of the element’s drawing surface; however, when you use CSS to size a canvas element, you set only the element’s size and not the drawing surface. When the canvas element’s size does not match the size of its drawing surface, the browser scales the drawing surface to fit the element.
设置元素的width
和height
属性时,既要设置元素的大小,又要设置元素的绘图表面的大小。 但是,当您使用CSS调整画布元素的大小时,您只能设置元素的大小,而不能设置绘图表面。 当画布元素的大小与其绘图表面的大小不匹配时,浏览器会缩放绘图表面以适合该元素。
Because of this, it’s a good idea to use the canvas element’s width
and height
attributes to size the element, instead of using CSS.
因此,最好使用canvas元素的width
和height
属性来调整元素的大小,而不是使用CSS。
了解画布坐标系 (Understanding the Canvas Coordinate System)
In a 2D space, positions are referenced using X and Y coordinates. The X axis extends horizontally, and the Y axis extends vertically. The center has a position x = 0
and y = 0
, that can also be expressed as (0, 0)
. This method of positioning objects, used in mathematics, is known as the Cartesian coordinate system.
在2D空间中,使用X和Y坐标引用位置。 X轴水平延伸,Y轴垂直延伸。 中心位置x = 0
和y = 0
,也可以表示为(0, 0)
。 数学中使用的这种对象定位方法称为笛卡尔坐标系 。
The Canvas coordinate system, however, places the origin at the upper-left corner of the canvas, with X coordinates increasing to the right and Y coordinates increasing toward the bottom of the canvas. So unlike a standard Cartesian coordinate space, the Canvas space doesn’t have visible negative points. Using negative coordinates won’t cause your application to fail, but objects positioned using negative coordinate points won’t appear on the page.
但是,“画布”坐标系将原点放置在画布的左上角,其中X坐标向右增加,Y坐标向画布的底部增加。 因此,与标准的笛卡尔坐标空间不同,画布空间没有可见的负点。 使用负坐标不会导致您的应用程序失败,但是使用负坐标点定位的对象不会出现在页面上。
基本画布示例 (Basic Canvas Examples)
As mentioned, HTML5 Canvas let’s you create many types of objects, including lines, curves, paths, shapes, text, etc. In the examples to follow you can see how some of these objects are actually drawn. I won’t go in extensive detail on the Canvas API; these are just some easy to help you get a feel for how canvas works.
如前所述,HTML5 Canvas让您创建许多类型的对象,包括直线,曲线,路径,形状,文本等。在下面的示例中,您可以看到这些对象的实际绘制方式。 我不会在Canvas API上进行详细介绍。 这些只是一些简单的方法,可以帮助您了解画布的工作原理。
画线 (Drawing Lines)
To draw a line, we use four canvas API methods. We start with the beginPath()
method which instructs the browser to prepare to draw a new path. Next, we use the moveTo(x, y)
method to set the line’s starting point. Then lineTo(x, y)
method sets the ending point and draws the line by connecting the two points.
为了画一条线,我们使用了四种canvas API方法。 我们从beginPath()
方法开始,该方法指示浏览器准备绘制新路径。 接下来,我们使用moveTo(x, y)
方法设置直线的起点。 然后, lineTo(x, y)
方法设置终点,并通过连接两个点绘制直线。
At this point the line will be drawn, but it’s still invisible. To make it visible we use the stroke()
method to display the line with the default black color.
此时将画出线条,但仍不可见。 为了使其可见,我们使用stroke()
方法以默认的黑色显示行。
context.beginPath();
context.moveTo(50, 50);
context.lineTo(250, 150);
context.stroke();
See the Pen Canvas Line Example by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint ( @SitePoint )的Pen Canvas行示例 。
画矩形 (Draw Rectangle)
To draw a rectangle, we can use the fillRect(x, y, width, height)
method to set the coordinates and the dimensions, along with the fillStyle
property to set the fill color.
要绘制矩形,我们可以使用fillRect(x, y, width, height)
方法设置坐标和尺寸,并使用fillStyle
属性设置填充颜色。
context.fillStyle = 'yellow';
context.fillRect(50, 50, 200, 100);
See the Pen Canvas Rectangle Example by SitePoint (@SitePoint) on CodePen.
请参见CodePen上的SitePoint ( @SitePoint )的Pen Canvas Rectangle示例 。
Notice that the rectangle is positioned near the top left corner.
请注意,矩形位于左上角附近。
绘制文字 (Draw Text)
To draw text on the canvas, we can use fillText(string, x, y)
along with the font
property to set the font, size, and style of the text (similar to font shorthand in CSS).
要在画布上绘制文本,我们可以使用fillText(string, x, y)
以及font
属性来设置文本的字体,大小和样式(类似于CSS中的字体缩写)。
context.font = 'italic 40pt Calibri, sans-serif';
context.fillText('Hello World!', 50, 50);
See the Pen Canvas Text Example by SitePoint (@SitePoint) on CodePen.
请参见CodePen上的SitePoint ( @SitePoint )提供的Pen Canvas文本示例 。
You should be aware that although simple drawing with the HTML5 Canvas API is easy, creating complex shapes and animations requires some Maths and Physics knowledge. One of the best books on this topic is Foundation HTML5 Animation with JavaScript. This book is a great resource for learning to move things, from simple to complex animations.
您应该知道,尽管使用HTML5 Canvas API进行简单绘制很容易,但是创建复杂的形状和动画需要一些数学和物理知识。 关于此主题的最佳书籍之一是带有JavaScript的Foundation HTML5动画 。 这本书是学习将事物从简单动画过渡到复杂动画的绝佳资源。
在哪里了解更多? (Where to Learn More?)
If you want to learn here are some resources:
如果您想在这里学习一些资源:
Canvas tutorial – An excellent tutorial on MDN, full of examples, illustrations, and detailed explanations.
画布教程 –关于MDN的优秀教程,其中包含示例,插图和详细说明。
HTML5 Canvas Element Guide – A beginner’s tutorial from Six Revisions.
HTML5 Canvas元素指南 –六个修订版的初学者教程。
HTML5 Canvas tutorials – A full set of tutorials created by Eric Rowell, the creator of the KineticJS canvas library. All examples are interactive; you can play with them and see the result immediately.
HTML5 Canvas教程 –由KineticJS画布库的创建者Eric Rowell创建的全套教程。 所有示例都是交互式的。 您可以和他们一起玩,并立即查看结果。
加快画布开发 (Speed Up Canvas Development)
Working with the “raw” HTML5 Canvas API can be a tedious job. That’s why it’s a good idea when you learn it well to switch to a good canvas library that can speed up and make your canvas development a lot easier.
使用“原始” HTML5 Canvas API可能是一件乏味的工作。 这就是为什么当您很好地学习并切换到可以加速并简化画布开发的良好画布库时,这是一个好主意的原因。
Here are some popular choices:
以下是一些受欢迎的选择:
Another way to speed up your HTML5 Canvas development is by using the Ai->Canvas plugin for Adobe Illustrator. You can find an overview of the plugin in this article on SitePoint.
加快HTML5 Canvas开发速度的另一种方法是使用Adobe Illustrator的Ai-> Canvas插件 。 您可以在SitePoint上的本文中找到该插件的概述。
结论 (Conclusion)
That’s it. I hope this introductory HTML5 Canvas tutorial has given you a good starting point from which to continue your learning and exploring of this powerful technology.
而已。 希望本入门HTML5 Canvas教程为您提供一个良好的起点,从那里您可以继续学习和探索这种强大的技术。
翻译自: https://www.sitepoint.com/html5-canvas-tutorial-introduction/
html2canvas教程