您的位置:首页 > 其它

Basic usage about Canvas

2012-08-28 17:53 232 查看
<canvas>元素
Let'sstartthistutorialbylookingatthe
<canvas>
elementitself.

让我们从
<canvas>
元素的定义开始吧。

<canvasid="tutorial"width="150"height="150"></canvas>

Thislooksalotlikethe
<img>
element,theonlydifferenceisthatitdoesn'thavethe
src
and
alt
attributes.The
<canvas>
elementhasonlytwoattributes-widthand
height.ThesearebothoptionalandcanalsobesetusingDOMpropertiesorCSSrules.Whennowidthandheight
attributesarespecified,thecanvaswillinitiallybe300pixelswideand
150pixelshigh.TheelementcanbesizedarbitrarilybyCSS,butduringrenderingtheimageisscaledtofititslayoutsize.(Ifyourrenderingsseemdistorted,tryspecifyingyourwidth
andheightattributesexplicitlyinthe
<canvas>
attributes,andnotwithCSS.)
<canvas>看起来很像<img>,唯一不同就是它不含
src
alt
属性。它只有两个属性,widthheight,两个都是可选的,并且都可以DOM或者CSS来设置。如果不指定width
和height,默认的是宽300像素高150像素。虽然可以通过
CSS来调整canvas的大小,但渲染图像会缩放来适应布局的(如果你发现渲染结果看上去变形了,不必一味依赖CSS,可以尝试显式指定canvas的width和height属性值)。

The
id
attributeisn'tspecifictothe
<canvas>
elementbutisoneofdefaultHTMLattributeswhichcanbeappliedto(almost)everyHTMLelement(like
class
forinstance).It'salwaysagoodideatosupplyanidbecause
thismakesitmucheasiertoidentifyitinourscript.

id
属性不是
<canvas>
专享的,就像标准的HTML标签一样,任何一个HTML元素都可以指定其
id
值。一般,为元素指定
id
是个不错的主意,这样使得在脚本中应用更加方便。

The
<canvas>
elementcanbestyledjustlikeanynormalimage(margin,border,background,etc).Theseruleshoweverdon'taffecttheactualdrawingonthecanvas.We'llseehowthisisdonelaterinthistutorial.Whennostylingrulesare
appliedtothecanvasitwillinitiallybefullytransparent.


<canvas>
元素可以像普通图片一样指定其样式(边距,边框,背景等等)。然而这些样式并不会对canvas实际生成的图像产生什么影响。下面我们会看到如何应用样式。如果不指定样式,canvas默认是全透明的。

替用内容

Becausethe
<canvas>
elementisstillrelativelynewandisn'timplementedinsomebrowsers(suchasFirefox1.0andInternetExplorer),weneedameansofprovidingfallbackcontentwhenabrowserdoesn'tsupporttheelement.

因为
<canvas>
相对较新,有些浏览器并没实现,如Firefox1.0和InternetExplorer,所以我们需要为那些不支持canvas的浏览器提供替用显示内容。

Luckilythisisverystraightforward:wejustprovidealternativecontentinsidethecanvaselement.Browserswhodon'tsupportitwillignoretheelementcompletelyandrenderthefallbackcontent,otherswilljustrenderthecanvasnormally.

Forinstancewecouldprovideatextdescriptionofthecanvascontentorprovideastaticimageofthedynamicallyrenderedcontent.Thiscanlooksomethinglikethis:

我们只需要直接在canvas元素内插入替用内容即可。不支持canvas的浏览器会忽略canvas元素而直接渲染替用内容,而支持的浏览器则会正常地渲染canvas。例如,我们可以把一些文字或图片填入canvas内,作为替用内容:

<canvasid="stockGraph"width="150"height="150">
currentstockprice:$3.15+0.15
</canvas>

<canvasid="clock"width="150"height="150">
<imgsrc="images/clock.png"width="150"height="150"/>
</canvas>


结束标签
</canvas>
是必须的

IntheAppleSafariimplementation,
<canvas>
isanelementimplementedinmuchthesameway
<img>
is;itdoesnothaveanendtag.However,for
<canvas>
tohavewidespreaduseontheweb,somefacilityforfallbackcontentmustbeprovided.Therefore,Mozilla'simplementationrequiresanendtag(
</canvas>
).

在AppleSafari里,
<canvas>
的实现跟
<img>
很相似,它没有结束标签。然而,为了使
<canvas>
能在web的世界里广泛适用,需要给替用内容提供一个容身之所,因此,在Mozilla的实现里结束标签(
</canvas>
)是必须的。

Iffallbackcontentisnotneeded,asimple
<canvasid="foo"...></canvas>
willbefullycompatiblewithbothSafariandMozilla--Safariwillsimplyignoretheendtag.

如果没有替用内容,
<canvasid="foo"...></canvas>
对Safari和Mozilla是完全兼容的——Safari会简单地忽略结束标签。

Iffallbackcontentisdesired,someCSStricksmustbeemployedtomaskthefallbackcontentfromSafari(whichshouldrenderjustthecanvas),andalsotomasktheCSStricksthemselvesfromIE(whichshouldrenderthefallbackcontent).

如果有替用内容,那么可以用一些CSS技巧来为并且仅为Safari隐藏替用内容,因为那些替用内容是需要在IE里显示但不需要在Safari里显示。


渲染上下文(RenderingContext)

<canvas>
createsafixedsizedrawingsurfacethatexposesoneormorerenderingcontexts,whichareusedtocreateandmanipulatethecontentshown.We'llfocusonthe2Drenderingcontext,whichistheonlycurrentlydefinedrendering
context.Inthefuture,othercontextsmayprovidedifferenttypesofrendering;forexample,itislikelythata3Dcontextbasedon

OpenGLESwillbeadded.

<canvas>
创建的固定尺寸的绘图画面开放了一个或多个渲染上下文(renderingcontext),我们可以通过它们来控制要显示的内容。我们专注于2D渲染上,这也是目前唯一的选择,可能在将来会添加基于OpenGLES
的3D上下文。

The
<canvas>
isinitiallyblank,andtodisplaysomethingascriptfirstneedstoaccesstherenderingcontextanddrawonit.ThecanvaselementhasaDOMmethodcalled
getContext
,usedtoobtaintherenderingcontextanditsdrawing
functions.
getContext()
takesoneparameter,thetypeofcontext.

<canvas>
初始化是空白的,要在上面用脚本画图首先需要其渲染上下文(renderingcontext),它可以通过canvas元素对象的
getContext
方法来获取,同时得到的还有一些画图用的函数。
getContext()
接受一个用于描述其类型的值作为参数。

varcanvas=document.getElementById('tutorial');
varctx=canvas.getContext('2d');

InthefirstlineweretrievethecanvasDOMnodeusingthe
getElementByIdmethod.Wecanthenaccessthedrawingcontextusingthe
getContext
method.

上面第一行通过
getElementById方法取得canvas对象的DOM节点。然后通过其
getContext
方法取得其画图操作上下文。


检查浏览器的支持

Thefallbackcontentisdisplayedinbrowserswhichdonotsupport
<canvas>
;scriptscanalsocheckforsupportwhentheyexecute.Thiscaneasilybedonebytestingforthe
getContext
method.Ourcodesnippetfromabovebecomes
somethinglikethis:

除了在那些不支持的浏览器上显示替用内容,还可以通过脚本的方式来检查浏览器是否支持canvas。方法很简单,判断
getContext
是否存在即可。

varcanvas=document.getElementById('tutorial');
if(canvas.getContext){
varctx=canvas.getContext('2d');
//drawingcodehere
}else{
//canvas-unsupportedcodehere
}

代码模板

Hereisaminimalistictemplate,whichwe'llbeusingasastartingpointforlaterexamples.Youcandownload
thisfiletoworkwithonyoursystem.

我们会用下面这个最简化的代码模板来(后续的示例需要用到)作为开始,你可以
下载文件到本地备用。

<html>
<head>
<title>Canvastutorial</title>
<scripttype="text/javascript">
functiondraw(){
varcanvas=document.getElementById('tutorial');
if(canvas.getContext){
varctx=canvas.getContext('2d');
}
}
</script>
<styletype="text/css">
canvas{border:1pxsolidblack;}
</style>
</head>
<bodyonload="draw();">
<canvasid="tutorial"width="150"height="150"></canvas></body>
</html>

Ifyoulookatthescriptyou'llseeI'vemadeafunctioncalled
draw
,whichwillgetexecutedoncethepagefinishesloading(viathe
onload
attributeonthe
body
tag).ThisfunctioncouldalsohavebeencalledfromasetTimeout,

setInterval,oranyothereventhandlerfunctionjustaslongthepagehasbeenloadedfirst.

细心的你会发现我准备了一个名为
draw
的函数,它会在页面装载完毕之后执行一次(通过设置
body
标签的
onload
属性),它当然也可以在

setTimeout,setInterval,或者其他事件处理函数中被调用。

原文网址:https://developer.mozilla.org/zh-CN/docs/Canvas_tutorial/Basic_usage

一个简单的例子

Tostartoff,here'sasimpleexamplethatdrawstwointersectingrectangles,oneofwhichhasalphatransparency.We'llexplorehowthisworksinmoredetailinlaterexamples.

作为开始,来一个简单的吧——绘制两个交错的矩形,其中一个是有alpha透明效果。我们会在后面的示例中详细的让你了解它是如何运作的。



观看示例

<html>
<head>
<scripttype="application/x-javascript">
functiondraw(){
varcanvas=document.getElementById("canvas");
if(canvas.getContext){
varctx=canvas.getContext("2d");

ctx.fillStyle="rgb(200,0,0)";
ctx.fillRect(10,10,55,50);

ctx.fillStyle="rgba(0,0,200,0.5)";
ctx.fillRect(30,30,55,50);
}
}
</script>
</head>
<bodyonload="draw();">
<canvasid="canvas"width="150"height="150"></canvas>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: