Canvas

Canvas

Intro

Intro (简介)

This tutorial describes how to use the canvas element to draw 2D graphics starting with the basics. The provided examples should give you some clear ideas about what you can do with canvas and will provide code snippets that may get you started in building your own content. (本教程介绍如何使用画布元素从基础知识开始绘制2D图形。所提供的示例应为您提供一些关于可以使用画布做什么的清晰想法,并提供可以帮助您开始构建自己的内容的代码片段。)

Using the canvas element is not very difficult but you do need a basic understanding of HTML and JavaScript. The canvas element is not supported in some older browsers but is supported in recent versions of all major browsers. The default size of the canvas is 300 px × 150 px (width × height). But custom sizes can be defined using the CSS height and width property. To draw graphics on the canvas, we use a JavaScript context object which creates graphics on the fly. (使用画布元素并不困难,但您确实需要对HTML和JavaScript有基本的了解。某些较旧的浏览器不支持canvas元素,但所有主要浏览器的最新版本都支持该元素。画布的默认大小为300像素× 150像素(宽×高)。但是,可以使用CSS高度和宽度属性定义自定义大小。为了在画布上绘制图形,我们使用JavaScript上下文对象即时创建图形。)

  • Drawing Paths (-绘图路径)

  • Drawing Arcs (-绘制弧线)

  • Drawing Texts (-绘图文本)

  • Drawing Images (-绘制图像)

Usage

Usage (使用)

The canvas element has only two attributes: width and height.The id attribute isn’t specific to the canvas element but is one of the global HTML attributes which can be applied to any HTML element (like class for instance).

Let’s see how the canvas looks like in html. (让我们看看画布在html中的样子。)

<canvas id="tutorial" width="150" height="150"></canvas>

getContext()

getContext() (getContext ())

The canvas is initially blank. To display something, first of all, a script needs to access the rendering context and draw on it. The canvas element has a method called getContext(), used to obtain the rendering context and its drawing functions. getContext() takes one parameter: the type of context. For 2D graphics, such as those covered by this tutorial, you specify “2d” to get a CanvasRenderingContext2D.

let canvas = document.getElementById('tutorial');
let ctx = canvas.getContext('2d');

Drawing Rectangles

Drawing Rectangles (绘制矩形)

The ctx.fillRect() method of the Canvas 2D API draws a filled rectangle at (x, y) position whose size is determined by width and height and whose style is determined by the fillStyle attribute. (Canvas 2D API的ctx.fillRect ()方法在(x, y)位置绘制一个填充矩形,其大小由宽度和高度决定,其样式由fillStyle属性决定。)

Syntax

Syntax (语法)

void ctx.fillRect(x, y, width, height);

Let’s see a simple example. (让我们看一个简单的例子。)

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
   <style type="text/css">
     canvas {
       border: 1px solid black;
     }
   </style>
 </head>
 <body onload="paint()">
   <script type="text/javascript">
     function paint() {
       let canvas = document.getElementById('tutorial');
       let ctx = canvas.getContext('2d');
       ctx.fillStyle = "green";
       ctx.fillRect(10, 10, 100, 100);
     }
   </script>
   <canvas id="tutorial" width="250" height="250"></canvas>
 </body>
</html>

Here is some functions about drawing rectangles. (以下是有关绘制矩形的一些功能。)

FunctionDescription
strokeRect(x, y, width, height)Draws a rectangular outline.
clearRect(x, y, width, height)Clears the specified rectangular area, making it fully transparent.

Drawing Paths

Drawing Paths (绘图路径)

The other primitive shapes are paths. A path is a list of points, connected by segments of lines that can be of different shapes, curved or not curved, of different width and different color. (其他基本形状是路径。路径是一个点列表,由不同形状(曲线或非曲线)、不同宽度和不同颜色的线段连接。)

The first step is to begin drawing. (第一步是开始绘画。)

beginPath()

Creates a new path. Once created, future drawing commands are directed into the path and used to build the path up. (创建新路径。创建后,未来的绘图命令将被引导到路径中,并用于构建路径。)

moveTo()

The method of the Canvas 2D API moves the starting point of a new sub-path to the (x, y) coordinates. (Canvas 2D API的方法将新子路径的起点移动到(x, y)坐标。)

Syntax

Syntax (语法)

void ctx.moveTo(x, y);

lineTo()

The method of the Canvas 2D API connects the last point in the sub-path to the x, y coordinates with a straight line (but does not actually draw it). (Canvas 2D API的方法使用直线将子路径中的最后一个点连接到x, y坐标(但实际上并不绘制它)。)

syntax

syntax (语法)

void ctx.lineTo(x, y);

Let’s see a simple example. (让我们看一个简单的例子。)

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
   <style type="text/css">
     canvas {
       border: 1px solid black;
     }
   </style>
 </head>
 <body onload="paint()">
   <script type="text/javascript">
     function paint() {
       let canvas = document.getElementById("canvas");
       let ctx = canvas.getContext("2d");
       ctx.beginPath();
       ctx.moveTo(0, 0);
       ctx.lineTo(250, 250);
       ctx.stroke();
     }
   </script>
   <canvas id="canvas" width="250" height="250"></canvas>
 </body>
</html>

Here is some functions drawing paths. (以下是一些绘制路径的函数。)

FunctionDescription
closePath()Closes the path so that future drawing commands are once again directed to the context.
stroke()Draws the shape by stroking its outline.
fill()Draws a solid shape by filling the paths content area.

Drawing Arcs

Drawing Arcs (绘图弧线)

We use the arc() or arcTo() methods in order to draw arcs or circles. (我们使用arc ()或arcTo ()方法来绘制弧或圆。)

arc()

The method of the Canvas 2D API adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise). (Canvas 2D API的方法为以(x, y)位置为中心的路径添加一个圆弧,半径r从startAngle开始,到endAngle结束,逆时针方向(默认为顺时针)。)

Syntax

Syntax (语法)

void ctx.arc (x, y, radius, startAngle, endAngle, anticlockwise);

Let’s see an example. (让我们看一个例子。)

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
   <style type="text/css">
     canvas {
       border: 1px solid black;
     }
   </style>
 </head>
 <body onload="paint()">
   <script type="text/javascript">
     function paint() {
       let canvas = document.getElementById("canvas");
       let ctx = canvas.getContext("2d");
       ctx.beginPath();
       ctx.arc(100, 75, 50, 0, 2 * Math.PI);
       ctx.stroke();
     }
   </script>
   <canvas id="canvas" width="250" height="250"></canvas>
 </body>
</html>

Drawing Texts

Drawing Texts (绘图文本)

Now it’s time to talk a little about drawing texts. (现在是时候谈谈绘制文本了。)

fillText()

The method of the Canvas 2D API fills a given text at the given (x, y) position. If the optional fourth parameter for a maximum width is provided the text will be scaled to fit that width. (Canvas 2D API的方法在给定的(x, y)位置填充给定的文本。如果提供了最大宽度的可选第四个参数,则将缩放文本以适应该宽度。)

Syntax

Syntax (语法)

void ctx.fillText(text, x, y [, maxWidth]);

Let’s see an example. (让我们看一个例子。)

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
   <style type="text/css">
     canvas {
       border: 1px solid black;
     }
   </style>
 </head>
 <body onload="paint()">
   <script type="text/javascript">
     function paint() {
       let canvas = document.getElementById("canvas");
       let ctx = canvas.getContext("2d");
       ctx.font = "40px serif";
       ctx.fillText("Hello w3cdoc", 10, 100);
     }
   </script>
   <canvas id="canvas" width="250" height="250"></canvas>
 </body>
</html>

There is another function to draw text with javascript canvas.StrokeText function draws stroke style text. Here is its syntax.

strokeText(text, x, y [, maxWidth])

Drawing Images

Drawing Images (绘制图像)

Until now we have created our shapes and applied styles to them. One of the more exciting features of canvas is the ability to use images. These can be used to do dynamic photo composting or as backdrops of graphs, for sprites in games, and so forth. External images can be used in any format supported by the browser such as PNG, GIF, or JPEG. You can even use the image produced by other canvas elements on the same page as the source! (到目前为止,我们已经创建了形状并对其应用了样式。画布的一个更令人兴奋的功能是能够使用图像。这些可用于进行动态照片堆肥或作为图形的背景,用于游戏中的精灵等。外部图像可用于浏览器支持的任何格式,如PNG、GIF或JPEG。您甚至可以在同一页面上使用其他画布元素生成的图像作为源!)

DrawImage()

The method of the Canvas 2D API provides different ways to draw an image onto the canvas. (Canvas 2D API的方法提供了在画布上绘制图像的不同方法。)

Syntax

Syntax (语法)

void ctx.drawImage(image, dx, dy);
void ctx.drawImage(image, dx, dy, dWidth, dHeight);
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

Let’s make an example. (让我们举个例子。)

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
   <style type="text/css">
     canvas {
       border: 1px solid black;
     }
   </style>
 </head>
 <body onload="paint()">
   <script type="text/javascript">
     function paint() {
       let canvas = document.getElementById("canvas");
       let ctx = canvas.getContext("2d");
       let img = new Image();
       img.onload = function() {
         ctx.drawImage(img, 0, 0);
       };
       img.src = 'http://www.w3cdoc.com/uploads/media/book_gallery/0001/01/066705b46be05dfdde77a1bc60c120b76257b553.png';
     }
   </script>
   <canvas id="canvas" width="250" height="250"></canvas>
 </body>
</html>

We can talk more and more about canvas, its methods and something else. There are many things connected with canvas and here is a list of that. (我们可以越来越多地谈论画布,它的方法和其他东西。有很多东西与画布有关,这里有一个列表。)

  • Transformations // save(), restore(), rotate(angle), translate(x, y), scale(x, y) etc… methods (- Transformations//save ()、restore ()、rotate (angle)、translate (x, y)、scale (x, y)等…方法)

  • Animations // with setInterval(), setTimeout(), requestAnimationFrame() etc… (-动画//使用setInterval ()、setTimeout ()、requestAnimationFrame ()等…)

  • Pixel manipulation // useing createImageData(), getImageData(), putImageData() etc… (-像素操作//使用createImageData ()、getImageData ()、putImageData ()等…)

  • etc… (- 等等。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部