Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5404263
  • 博文数量: 763
  • 博客积分: 12108
  • 博客等级: 上将
  • 技术积分: 15717
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-28 21:21
个人简介

业精于勤,荒于嬉

文章分类

全部博文(763)

文章存档

2018年(6)

2017年(15)

2016年(2)

2015年(31)

2014年(14)

2013年(87)

2012年(75)

2011年(94)

2010年(190)

2009年(38)

2008年(183)

2007年(28)

分类: 系统运维

2011-07-05 12:00:02

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

   

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

<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部分中,或者放在外部文件中。

阅读(1575) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~