资源描述:
《创建 canvas 的方法很简单.docx》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、创建canvas的方法很简单,只需要在HTML页面中添加
2、上下文API绘制各种图形。下面的脚本在canvas中绘制一个矩形(点击此处查看效果):12345678910111213141516//Getareferencetotheelement.var elem = document.getElementById('myCanvas'); //Alwayscheckforproperties和methods,tomakesureyourcodedoesn'tbreak //inotherbrowsers.if (elem && elem.getContext) { //Getthe2dcontext.
3、//Remember:youcanonlyinitializeonecontextperelement. var context = elem.getContext('2d'); if (context) { //Youaredone!Nowyoucandrawyourfirstrectangle. //Youonlyneedtoprovidethe(x,y)coordinates,followedbythewidthand //heightdimensions. context.fillRect(0, 0, 150, 100); }}可以把上
4、面代码放置在文档head部分中,或者放在外部文件中。2DcontextAPI介绍了如何创建canvas后,让我们来看看2DcanvasAPI,看看能用这些函数做些什么。基本线条上面的例子中展示了绘制矩形是多么简单。通过 fillStyle 和 strokeStyle 属性可以轻松的设置矩形的填充和线条。颜色值使用方法和 CSS 一样:十六进制数、rgb()、rgba()和 hsla()(若浏览器支持,如Opera10 和Firefox3)。通过fillRect可以绘制带填充的矩形。使用strokeRect可以绘制只有边框没有填充的矩形。如果想清除部分canvas可以
5、使用clearRect。上述三个方法的参数相同:x, y, width, height。前两个参数设定(x,y)坐标,后两个参数设置矩形的高度和宽度。可以使用 lineWidth 属性改变线条粗细。让我们看看使用了fillRect,strokeRectclearRect和其他的例子:123456789context.fillStyle = '#00f'; //bluecontext.strokeStyle = '#f00'; //redcontext.lineWidth = 4; //Drawsomerectangles.context.fillRect
6、(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即可
7、添加填充或者设置边框。调用closePath()结束自定义图形绘制。下面是一个绘制三角形的例子:12345678910//Setthestyleproperties.context.fillStyle = '#00f';context.strokeStyle = '#f00';context.lineWidth = 4; context.beginPath();//Startfromthetop-leftpoint.context.moveTo(10, 10); //givethe(x,y)coordinatescontext.lineTo(100, 1