首页 > 开发 > HTML > 正文

HTML 5 canvas 基本语法

2020-09-18 22:11:27
字体:
来源:转载
供稿:网友

html 5 canvas —— 基本语法

简述

5 规范引进了很多新特性,其中最令人期待的之一就是 canvas 元素。html 5 canvas 提供了通过 javascript 绘制图形的方法,此方法使用简单但功能强大。每一个 canvas 元素都有一个"上下文( context )" (想象成绘图板上的一页),在其中可以绘制任意图形。浏览器支持多个 canvas 上下文,并通过不同的 提供图形绘制功能。 提供图形绘制功能。 5 规范引进了很多新特性,其中最令人期待的之一就是 元素。html 5 提供了通过 javascript 绘制图形的方法,此方法使用简单但功能强大。每一个 元素都有一个"上下文( context )" (想象成绘图板上的一页),在其中可以绘制任意图形。浏览器支持多个 canvas 上下文,并通过不同的 提供图形绘制功能。

大部分的浏览器都支持 2d canvas 上下文——包括 opera, firefox, konqueror 和 safari。而且某些版本的 opera 还支持 3d canvas ,firefox 也可以通过插件形式支持 3d canvas :

  • 下载支持 3d canvas, html video 和 file i/o 的 opera
  • 关于 opera 3d canvas 上下文的文章
  • 关于 firefox 3d canvas
    上下文的文章

本文介绍 2d canvas
基础以及如何使用基本 canvas 函数,如线条、形状、图像和文字等。为了理解此文章,你最好了解 javascript 基础知识。

可以点击此处批量下载本文实例代码

canvas 基础

创建 canvas 的方法很简单,只需要在 html 页面中添加 <canvas> 元素:

<canvas id="mycanvas" width="300" height="150">fallback content, in case the browser does not support canvas.</canvas>

为了能在 javascript 中引用元素,最好给元素设置 id ;也需要给 canvas 设定高度和宽度。

创建好了画布后,让我们来准备画笔。要在画布中绘制图形需要使用 javascript 。首先通过 getelementbyid 函数找到 canvas
元素,然后初始化上下文。之后可以使用上下文 api 绘制各种图形。下面的脚本在 canvas 中绘制一个矩形 (点击此处查看效果):

// get a reference to the element.var elem = document.getelementbyid('mycanvas');// always check for properties 和 methods, to make sure your code doesn't break // in other browsers.if (elem && elem.getcontext) {  // get the 2d context.  // remember: you can only initialize one context per element.  var context = elem.getcontext('2d');  if (context) {    // you are done! now you can draw your first rectangle.    // you only need to provide the (x,y) coordinates, followed by the width and     // height dimensions.    context.fillrect(0, 0, 150, 100);  }}

可以把上面代码放置在文档 head 部分中,或者放在外部文件中。

2d context api

介绍了如何创建 canvas 后,让我们来看看 2d canvas api,看看能用这些函数做些什么。

基本线条

上面的例子中展示了绘制矩形是多么简单。

通过 fillstylestrokestyle 属性可以轻松的设置矩形的填充和线条。颜色值使用方法和 十六进制数、()、() 和 ()( 若浏览器支持,如 opera
10 和 firefox 3)。()( 若浏览器支持,如 opera10 和 firefox 3)。() 和 ()( 若浏览器支持,如 opera10 和 firefox 3)。()、() 和 ()( 若浏览器支持,如 opera10 和 firefox 3)。十六进制数、()、() 和 ()( 若浏览器支持,如 opera10 和 firefox 3)。

通过 fillrect 可以绘制带填充的矩形。使用 strokerect 可以绘制只有边框没有填充的矩形。如果想清除部分 canvas 可以使用 clearrect。上述三个方法的参数相同:x, y, width, height。前两个参数设定 (x,y) 坐标,后两个参数设置矩形的高度和宽度。

可以使用 linewidth 属性改变线条粗细。让我们看看使用了fillrect,
strokerect clearrect 和其他的例子:

context.fillstyle   = '#00f'; // bluecontext.strokestyle = '#f00'; // redcontext.linewidth   = 4;// draw some rectangles.context.fillrect  (0,   0, 150, 50);context.strokerect(0,  60, 150, 50);context.clearrect (30, 25,  90, 60);context.strokerect(30, 25,  90, 60);

此例子效果图见图1.

example render of fillrect, strokerect and clearrect.

图 1: fillrect, strokerect 和
clearrect效果图

路径

通过 canvas 路径(path)可以绘制任意形状。可以先绘制轮廓,然后绘制边框和填充。创建自定义形状很简单,使用 beginpath()开始绘制,然后使用直线、曲线和其他图形绘制你的图形。绘制完毕后调用 fillstroke 即可添加填充或者设置边框。调用 closepath() 结束自定义图形绘制。

下面是一个绘制三角形的例子:

// set the style properties.context.fillstyle   = '#00f';context.strokestyle = '#f00';context.linewidth   = 4;context.beginpath();// start from the top-left point.context.moveto(10, 10); // give the (x,y) coordinatescontext.lineto(100, 10);context.lineto(10, 100);context.lineto(10, 10);// done! now fill the shape, 和 draw the stroke.// note: your shape will not be visible until you call any of the two methods.context.fill();context.stroke();context.closepath();

其效果图见图2.

triangle

图 2: 三角形

另一个较负责的例子中使用了直线、曲线和圆弧。

插入图像

drawimage 方法允许在 canvas 中插入其他图像
( imgcanvas 元素) 。在 opera 中可以再 canvas 中绘制 svg 图形。此方法比较复杂,可以有3个、5个或9个参数:

  • 3个参数:最基本的 drawimage 使用方法。一个参数指定图像位置,另两个参数设置图像在 canvas中的位置。
  • 5个参数:中级的 drawimage 使用方法,包括上面所述3个参数,加两个参数指明插入图像宽度和高度 (如果你想改变图像大小)。
  • 9个参数:最复杂 drawimage 杂使用方法,包含上述5个参数外,另外4个参数设置源图像中的位置和高度宽度。这些参数允许你在显示图像前动态裁剪源图像。

下面是上述三个使用方法的例子:

// three arguments: the element, destination (x,y) coordinates.context.drawimage(img_elem, dx, dy);// five arguments: the element, destination (x,y) coordinates, and destination // width and height (if you want to resize the source image).context.drawimage(img_elem, dx, dy, dw, dh);// nine arguments: the element, source (x,y) coordinates, source width and // height (for cropping), destination (x,y) coordinates, and destination width // and height (resize).context.drawimage(img_elem, sx, sy, sw, sh, dx, dy, dw, dh);

其效果见图3.

example rendering of drawimage.

图 3: drawimage 效果图。

像素级操作

2d context api 提供了三个方法用于像素级操作:createimagedata, getimagedata, 和
putimagedata

imagedata对象保存了图像像素值。每个对象有三个属性: width, height
datadata 属性类型为canvaspixelarray,用于储存width*height*4个像素值。每一个像素有rgb值和透明度alpha值(其值为 0 至
255,包括alpha在内!)。像素的顺序从左至右,从上到下,按行存储。

为了更好的理解其原理,让我们来看一个例子——绘制红色矩形

// create an imagedata object.var imgd = context.createimagedata(50,50);var pix = imgd.data;// loop over each pixel 和 set a transparent red.for (var i = 0; n = pix.length, i < n; i += 4) {  pix[i  ] = 255; // red channel  pix[i+3] = 127; // alpha channel}// draw the imagedata object at the given (x,y) coordinates.context.putimagedata(imgd, 0,0);

注意: 不是所有浏览器都实现了 createimagedata。在支持的浏览器中,需要通过 getimagedata 方法获取 imagedata 对象。请参考示例代码。

通过 imagedata 可以完成很多功能。如可以实现图像滤镜,或可以实现数学可视化 (如分形和其他特效)。下面特效实现了简单的颜色反转滤镜:

// get the canvaspixelarray from the given coordinates and dimensions.var imgd = context.getimagedata(x, y, width, height);var pix = imgd.data;// loop over each pixel and invert the color.for (var i = 0, n = pix.length; i < n; i += 4) {  pix[i  ] = 255 - pix[i  ]; // red  pix[i+1] = 255 - pix[i+1]; // green  pix[i+2] = 255 - pix[i+2]; // blue  // i+3 is alpha (the fourth element)}// draw the imagedata at the given (x,y) coordinates.context.putimagedata(imgd, x, y);

图 4 显示了使用此滤镜后的 opera
图像 (图 3是原图)。

example rendering of the invert color filter.

图 4: 颜色反转滤镜

文字

虽然最近的 webkit 版本和 firefox 3.1 nightly build 才开始支持 text api ,为了保证文章完整性我决定仍在这里介绍文字 api 。

context 对象可以设置以下 text 属性:

  • font:文字字体,同
    font-family 属性 属性
  • textalign:文字水平对齐方式。可取属性值: start, end, left,
    right, center。默认值:
    start.
  • textbaseline:文字竖直对齐方式。可取属性值:top, hanging, middle,
    alphabetic, ideographic, bottom。默认值:alphabetic.

有两个方法可以绘制文字: filltextstroketext。第一个绘制带 fillstyle 填充的文字,后者绘制只有 strokestyle 边框的文字。两者的参数相同:要绘制的文字和文字的位置(x,y) 坐标。还有一个可选选项——最大宽度。如果需要的话,浏览器会缩减文字以让它适应指定宽度。

文字对齐属性影响文字与设置的
(x,y) 坐标的相对位置。

下面是一个在 canvas 中绘制"hello world" 文字的例子

context.fillstyle    = '#00f';context.font         = 'italic 30px sans-serif';context.textbaseline = 'top';context.filltext  ('hello world!', 0, 0);context.font         = 'bold 30px sans-serif';context.stroketext('hello world!', 0, 50);

图 5 是其效果图。

example text render.

图 5: 文字效果

阴影

目前只有 konqueror 和 firefox 3.1 nightly build 支持 shadows api 。api 的属性为:

  • shadowcolor:阴影颜色。其值和 css 颜色值一致。
  • shadowblur:设置阴影模糊程度。此值越大,阴影越模糊。其效果和 photoshop 的高斯模糊滤镜相同。
  • shadowoffsetxshadowoffsety:阴影的 x 和 y 偏移量,单位是像素。

下面是 canvas 阴影的例子:

context.shadowoffsetx = 5;context.shadowoffsety = 5;context.shadowblur    = 4;context.shadowcolor   = 'rgba(255, 0, 0, 0.5)';context.fillstyle     = '#00f';context.fillrect(20, 20, 150, 100);

其效果见图 6。

example canvas shadow - a blue rectangle with a red shadow.

图 6: canvas 阴影效果——蓝色矩形,红色阴影

颜色渐变

除了 css 颜色, fillstylestrokestyle 属性可以设置为 canvasgradient 对象。——通过 canvasgradient可以为线条和填充使用颜色渐变。

欲创建 canvasgradient 对象,可以使用两个方法:createlineargradientcreateradialgradient。前者创建线性颜色渐变,后者创建圆形颜色渐变。

创建颜色渐变对象后,可以使用对象的 addcolorstop 方法添加颜色中间值。

下面的代码演示了颜色渐变使用方法:

// you need to provide the source 和 destination (x,y) coordinates // for the gradient (from where it starts 和 where it ends).var gradient1 = context.createlineargradient(sx, sy, dx, dy);// now you can add colors in your gradient.// the first argument tells the position for the color in your gradient. the // accepted value range is from 0 (gradient start) to 1 (gradient end).// the second argument tells the color you want, using the css color format.gradient1.addcolorstop(0,   '#f00'); // redgradient1.addcolorstop(0.5, '#ff0'); // yellowgradient1.addcolorstop(1,   '#00f'); // blue// for the radial gradient you also need to provide source// 和 destination circle radius.// the (x,y) coordinates define the circle center points (start 和 // destination).var gradient2 = context.createradialgradient(sx, sy, sr, dx, dy, dr);// adding colors to a radial gradient is the same as adding colors to linear // gradients.

我也准备了一个更复杂的例子,使用了线性颜色渐变、阴影和文字。其效果见图 7。

example rendering using a linear gradient.

图 7: 使用线性颜色渐变的例子

canvas 演示

如果你想知道使用 canvas可以做些什么,可以参看以下的工程:

  • opera widget:
    • simaquarium
    • artist's
      sketchbook
    • spirograph
  • 在线工程和演示
    • newton polynomial
    • canvascape - "3d walker"
    • paint.web - painting
      demo, open-source
    • star-field
      flight
    • interactive blob

小节

canvas 是 html 5最让人期待的特性之一,目前已获得大部分 web 浏览器支持。canvas 可以帮助创建游戏、增强图形用户界面。2d context
api 提供大量图形绘制功能——我希望通过本文你了解了 canvas 使用,并且你有兴趣了解更多!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表