HTML5 Canvas:初始Canvas

Canvas HTML 5中引入它,可以做很多事情:画图、动画、游戏开发等等。

 

Canvas 元素

Canvas 中文翻译为:画布。

 

<canvas id=”yourCanvasId” width=”300” height=”150” />

Canvas元素除了公用属性外,只有两个额外的属性:width, height,他们都是没有单位的,其实单位是px,但是不能写单位。如果不指定这两个属性,默认是width300height150

众所周知,html元素的样式,都可以用css样式来指定。Canvas也不例外。

<html>
    <head>
        <title>Canvas - 01</title>
        <style>
            body{
                background:#dddddd;
            }

            #canvas{
                margin:20px;
                padding:20px;
                background:#ffffff;
                border:thin inset #aaaaaa;
                width:600px;
                height:300px;
            }
        </style>
    </head>
    <body>
        <canvas id="canvas">
            Canvas not supported
        </canvas>
        <script type="text/javascript">
            var canvas = document.getElementById("canvas"),
                ctx = canvas.getContext("2d");
            
            ctx.font='38pt Arial';
            ctx.fillStyle='cornflowerblue';
            ctx.strokeStyle='blue';
            ctx.fillText("Hello Canvas", canvas.width/2 -150, canvas.height/2 + 15);
            ctx.strokeText("Hello Canvas stroke", canvas.width/2 -200, canvas.height/2 + 80);
        </script>
    </body>
</html>

我们期望的结果是这样的: 

 

 

而实际的执行结果:

 

从执行结果看,它确实一个放大的hello,这是为什么呢?

 

其实我认为可以这样理解它,它是一个放映布,因为真正的绘图不在它上的,而是在一个绘图板上,绘图完毕投影到放映布上。这一点,类似于我们中学时候用过的幻灯片放映机,在一张玻璃板(绘图板)上写上习题,然后投影到放映布或者白墙上(画布)。

 所以呢,这样一想,就明白了,当css样式中的width,height属性值与canvas元素的width,height的属性值不同时,会自动的将绘图板上的内容进行缩放到画布上。

  

Canvas 元素目前有三个方法:

 

 

 

 

通过getContext(“2d”);能够取得CanvasRenderingContext2D对象,然后就可以基于此上下文对象来作2d图了

 通过getContext(“3d”);就可以进行3d作图,3d作图底层用的是WebGL

 

在随后的文章里,将会学习使用Canvas画图的必要知识。

CanvasRenderingContext2D API 详情:

http://www.w3school.com.cn/jsref/dom_obj_canvasrenderingcontext2d.asp

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D

http://www.w3school.com.cn/tags/html_ref_canvas.asp

http://www.html5canvastutorials.com/tutorials/html5-canvas-line-joins/

 高级教程:

包括event, arrow等理论基础 :http://www.dbp-consulting.com/tutorials/canvas/

posted @ 2017-08-16 14:14  乐享程序员  阅读(393)  评论(0编辑  收藏  举报