HTML5 canvas 新手入门教程

HTML5 canvas 新手入门教程

简述
HTML5 规范引进了很多新特性,其中最令人期待的之一就是 canvas 元素。HTML 5 canvas 提供了通过 JavaScript 绘制图形的方法,此方法使用简单但功能强大。每一个 canvas 元素都有一个"上下文( context )" (想象成绘图板上的一页),在其中可以绘制任意图形。浏览器支持多个 canvas 上下文,并通过不同的 API 提供图形绘制功能。大部分的浏览器都支持 2D canvas 上下文——包括 Opera, Firefox, Konqueror 和 Safari。而且某些版本的 Opera 还支持 3D canvas ,Firefox 也可以通过插件形式支持 3D canvas

本文介绍 2D canvas基础以及如何使用基本 canvas 函数,如线条、形状、图像和文字等。为了理解此文章,你最好了解 JavaScript 基础知识。
可以点击此处批量下载本文实例代码

 

 本文中的例子的超链接连接到网址全是HTML5网页,目前支持HTML5的浏览器有 Chrom,FireFox 3.6等,IE目前不支持HTML5,也就是说你用IE看本页面的一些例子的超链接是看不到的。

 

 

canvas 基础

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

复制内容到剪贴板
  1. <canvas id="myCanvas" width="300" height="150">    
  2. Fallback content, in case the browser does not support Canvas.    
  3. </canvas>  

 

为了能在 JavaScript 中引用元素,最好给元素设置 ID ;也需要给 canvas 设定高度和宽度。
创建好了画布后,让我们来准备画笔。要在画布中绘制图形需要使用 JavaScript 。首先通过 getElementById函数找到 canvas元素,然后初始化上下文。之后可以使用上下文 API 绘制各种图形。下面的脚本在 canvas 中绘制一个矩形 (点击此处查看效果):

 

复制内容到剪贴板
  1. // Get a reference to the element.    
  2. var elem = document.getElementById('myCanvas');    
  3.   
  4. // Always check for properties 和 methods, to make sure your code doesn't break     
  5. // in other browsers.    
  6. if (elem && elem.getContext) {    
  7.   // Get the 2d context.    
  8.   // Remember: you can only initialize one context per element.    
  9.   var context = elem.getContext('2d');    
  10.   if (context) {    
  11.     // You are done! Now you can draw your first rectangle.    
  12.     // You only need to provide the (x,y) coordinates, followed by the width and     
  13.     // height dimensions.    
  14.     context.fillRect(0, 0, 150, 100);    
  15.   }    
  16. }  

可以把上面代码放置在文档 head部分中,或者放在外部文件中。
2D context API
介绍了如何创建 canvas 后,让我们来看看 2D canvas API,看看能用这些函数做些什么。

基本线条

上面的例子中展示了绘制矩形是多么简单。
通过 fillStyle和 strokeStyle 属性可以轻松的设置矩形的填充和线条。颜色值使用方法和 CSS 一样:十六进制数、rgb()、rgba() 和 hsla。通过 fillRect可以绘制带填充的矩形。使用 strokeRect 可以绘制只有边框没有填充的矩形。如果想清除部分 canvas 可以使用 clearRect。上述三个方法的参数相同:x, y, width, height。前两个参数设定 (x,y) 坐标,后两个参数设置矩形的高度和宽度。可以使用 lineWidth属性改变线条粗细。让我们看看使用了fillRect,strokeRect clearRect 和其他的例子

复制内容到剪贴板
  1. context.fillStyle   = '#00f'; // blue    
  2. context.strokeStyle = '#f00'; // red    
  3. context.lineWidth   = 4;    
  4.   
  5. // Draw some rectangles.    
  6. context.fillRect  (0,   0, 150, 50);    
  7. context.strokeRect(0,  60, 150, 50);    
  8. context.clearRect (30, 25,  90, 60);    
  9. context.strokeRect(30, 25,  90, 60);  

 

此例子效果图见下图
图片

路径

通过 canvas 路径(path)可以绘制任意形状。可以先绘制轮廓,然后绘制边框和填充。创建自定义形状很简单,使用 beginPath()开始绘制,然后使用直线、曲线和其他图形绘制你的图形。绘制完毕后调用 fill 和 stroke 即可添加填充或者设置边框。调用 closePath() 结束自定义图形绘制。下面是一个绘制三角形的例子:

复制内容到剪贴板
  1. // Set the style properties.    
  2. context.fillStyle   = '#00f';    
  3. context.strokeStyle = '#f00';    
  4. context.lineWidth   = 4;    
  5.   
  6. context.beginPath();    
  7. // Start from the top-left point.    
  8. context.moveTo(10, 10); // give the (x,y) coordinates    
  9. context.lineTo(100, 10);    
  10. context.lineTo(10, 100);    
  11. context.lineTo(10, 10);    
  12.   
  13. // Done! Now fill the shape, 和 draw the stroke.    
  14. // Note: your shape will not be visible until you call any of the two methods.    
  15. context.fill();    
  16. context.stroke();    
  17. context.closePath();  

其效果图见下图
图片

另一个较复杂的例子中使用了直线、曲线和圆弧

插入图像

drawImage 方法允许在 canvas 中插入其他图像
( img 和 canvas 元素) 。在 Opera 中可以再 canvas 中绘制 SVG 图形。此方法比较复杂,可以有3个、5个或9个参数

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

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

复制内容到剪贴板
  1. // Three arguments: the element, destination (x,y) coordinates.    
  2. context.drawImage(img_elem, dx, dy);    
  3.   
  4. // Five arguments: the element, destination (x,y) coordinates, and destination     
  5. // width and height (if you want to resize the source image).    
  6. context.drawImage(img_elem, dx, dy, dw, dh);    
  7.   
  8. // Nine arguments: the element, source (x,y) coordinates, source width and     
  9. // height (for cropping), destination (x,y) coordinates, and destination width     
  10. // and height (resize).    
  11. context.drawImage(img_elem, sx, sy, sw, sh, dx, dy, dw, dh);  

其效果见下图
图片

像素级操作

2D Context API 提供了三个方法用于像素级操作:createImageData, getImageData, 和putImageData。ImageData对象保存了图像像素值。每个对象有三个属性: width, height 和data。data 属性类型为CanvasPixelArray,用于储存width*height*4个像素值。每一个像素有RGB值和透明度alpha值(其值为 0 至255,包括alpha在内!)。像素的顺序从左至右,从上到下,按行存储。为了更好的理解其原理,让我们来看一个例子——绘制红色矩形

 

复制内容到剪贴板
  1. // Create an ImageData object.    
  2. var imgd = context.createImageData(50,50);    
  3. var pix = imgd.data;    
  4.   
  5. // Loop over each pixel 和 set a transparent red.    
  6. for (var i = 0n = pix.length, i < n; i += 4) {    
  7.   pix[i  ] = 255; // red channel    
  8.   pix[i+3] = 127; // alpha channel    
  9. }    
  10.   
  11. // Draw the ImageData object at the given (x,y) coordinates.    
  12. context.putImageData(imgd, 0,0);   

注意: 不是所有浏览器都实现了 createImageData。在支持的浏览器中,需要通过 getImageData 方法获取 ImageData 对象。请参考示例代码
通过 ImageData可以完成很多功能。如可以实现图像滤镜,或可以实现数学可视化 (如分形和其他特效)。下面特效实现了简单的颜色反转滤镜

 

复制内容到剪贴板
  1. // Get the CanvasPixelArray from the given coordinates and dimensions.    
  2. var imgd = context.getImageData(x, y, width, height);    
  3. var pix = imgd.data;    
  4.   
  5. // Loop over each pixel and invert the color.    
  6. for (var i = 0n = pix.length; i < n; i += 4) {    
  7.   pix[i  ] = 255 - pix[i  ]; // red    
  8.   pix[i+1] = 255 - pix[i+1]; // green    
  9.   pix[i+2] = 255 - pix[i+2]; // blue    
  10.   // i+3 is alpha (the fourth element)    
  11. }    
  12.   
  13. // Draw the ImageData at the given (x,y) coordinates.    
  14. context.putImageData(imgd, x, y);  

下图显示了使用此滤镜后的效果
图片

文字

虽然最近的 WebKit 版本和 Firefox 3.1 nightly build 才开始支持 Text API ,为了保证文章完整性我决定仍在这里介绍文字 API 。
context对象可以设置以下 text 属性:

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

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

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

复制内容到剪贴板
  1. context.fillStyle    = '#00f';    
  2. context.font         = 'italic 30px sans-serif';    
  3. context.textBaseline = 'top';    
  4. context.fillText  ('Hello world!', 0, 0);    
  5. context.font         = 'bold 30px sans-serif';    
  6. context.strokeText('Hello world!', 0, 50);   

 

下图是其效果图
图片

阴影

目前只有 Konqueror 和 Firefox 3.1 nightly build 支持 Shadows API 。API 的属性为

shadowColor:阴影颜色。其值和 CSS 颜色值一致。
shadowBlur:设置阴影模糊程度。此值越大,阴影越模糊。其效果和 Photoshop 的高斯模糊滤镜相同。
shadowOffsetX 和 shadowOffsetY:阴影的 x 和 y 偏移量,单位是像素。

[url=http://www.robodesign.ro/coding/canvas-primer/20081208/example-shadows.html]下面是
canvas 阴影的例子[/url]:

复制内容到剪贴板
  1. context.shadowOffsetX = 5;    
  2. context.shadowOffsetY = 5;    
  3. context.shadowBlur    = 4;    
  4. context.shadowColor   = 'rgba(255, 0, 0, 0.5)';    
  5. context.fillStyle     = '#00f';    
  6. context.fillRect(20, 20, 150, 100);  

其效果见下图
图片

颜色渐变

除了 CSS 颜色, fillStyle和 strokeStyle 属性可以设置为 CanvasGradient 对象。——通过 CanvasGradient可以为线条和填充使用颜色渐变。欲创建 CanvasGradient对象,可以使用两个方法:createLinearGradient 和 createRadialGradient。前者创建线性颜色渐变,后者创建圆形颜色渐变。创建颜色渐变对象后,可以使用对象的 addColorStop方法添加颜色中间值。下面的代码演示了颜色渐变使用方法:

 

复制内容到剪贴板
  1. // You need to provide the source 和 destination (x,y) coordinates     
  2. // for the gradient (from where it starts 和 where it ends).    
  3. var gradient1 = context.createLinearGradient(sx, sy, dx, dy);    
  4.   
  5. // Now you can add colors in your gradient.    
  6. // The first argument tells the position for the color in your gradient. The     
  7. // accepted value range is from 0 (gradient start) to 1 (gradient end).    
  8. // The second argument tells the color you want, using the CSS color format.    
  9. gradient1.addColorStop(0,   '#f00'); // red    
  10. gradient1.addColorStop(0.5, '#ff0'); // yellow    
  11. gradient1.addColorStop(1,   '#00f'); // blue    
  12.   
  13. // For the radial gradient you also need to provide source    
  14. // 和 destination circle radius.    
  15. // The (x,y) coordinates define the circle center points (start 和     
  16. // destination).    
  17. var gradient2 = context.createRadialGradient(sx, sy, sr, dx, dy, dr);    
  18.   
  19. // Adding colors to a radial gradient is the same as adding colors to linear     
  20. // gradients.   

 

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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值