网站大量收购独家精品文档,联系QQ:2885784924

创建 canvas 方法很简单.docx

  1. 1、本文档共21页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
创建 canvas 的方法很简单,只需要在 HTML 页面中添加 canvas 元素:123canvas?id=myCanvas?width=300?height=150Fallback content, in case the browser does not support Canvas./canvas为了能在 JavaScript 中引用元素,最好给元素设置 ID ;也需要给 canvas 设定高度和宽度。创建好了画布后,让我们来准备画笔。要在画布中绘制图形需要使用 JavaScript 。首先通过 getElementById 函数找到 canvas元素,然后初始化上下文。之后可以使用上下文 API 绘制各种图形。下面的脚本在 canvas 中绘制一个矩形 (点击此处查看效果):12345678910111213141516// Get a reference to the element.var?elem?=?document.getElementById(myCanvas);?// Always check for properties 和 methods, to make sure your code doesnt break?// in other browsers.if?(elem?amp;amp;?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,看看能用这些函数做些什么。基本线条上面的例子中展示了绘制矩形是多么简单。通过?fillStyle?和?strokeStyle?属性可以轻松的设置矩形的填充和线条。颜色值使用方法和?CSS?一样:十六进制数、rgb()、rgba() 和?hsla()( 若浏览器支持,如Opera 10?和 Firefox 3)。通过 fillRect 可以绘制带填充的矩形。使用 strokeRect 可以绘制只有边框没有填充的矩形。如果想清除部分 canvas 可以使用 clearRect。上述三个方法的参数相同:x,?y,?width,?height。前两个参数设定 (x,y) 坐标,后两个参数设置矩形的高度和宽度。可以使用?lineWidth?属性改变线条粗细。让我们看看使用了fillRect,strokeRect clearRect 和其他的例子:123456789context.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.图 1: fillRect, strokeRect 和clearRect效果图路径通过 canvas 路径(path)可以绘制任意形状。可以先绘制轮廓,然后绘制边框和填充。创建自定义形状很简单,使用beginPath()开始绘制,然后使用直线、曲线和其他图形绘制你的图形。绘制完毕后调用 fill 和 stroke 即可添加填充或者设置边框。调用 closePath() 结束自定义图形绘制。下面是一个绘制三角形的例子:1234567891011121314151617// Set the style properties.context.fillStyle???=?#00f;context.strokeStyle?=?#f00;context.lineWi

文档评论(0)

xiaofei2001129 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档