下面例子為用canvas標(biāo)簽畫多條直線

字號(hào):


    代碼如下:
    <!doctype html public -//w3c//dtd xhtml 1.0 transitional//en http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>
    <html xmlns=http://www.w3.org/1999/xhtml>
    <head>
    <meta http-equiv=content-type content=text/html; charset=utf-8 />
    <title>index_three</title>
    <link href=css/style.css rel=stylesheet type=text/css/>
    <script type=text/javascript src=js/jquery-1.9.1.min.js></script>
    <script type=text/javascript src=js/index.js/></script>
    <body >
    <!-- 添加canvas標(biāo)簽,并加上紅色邊框以便于在頁(yè)面上查看 -->
    <canvas id=mycanvas width=400px height=300px style=border: 1px solid red;>
    您的瀏覽器不支持canvas標(biāo)簽。
    </canvas>
    <script type=text/javascript>
    //獲取canvas對(duì)象(畫布)
    var canvas = document.getelementbyid(mycanvas);
    //簡(jiǎn)單地檢測(cè)當(dāng)前瀏覽器是否支持canvas對(duì)象,以免在一些不支持html5的瀏覽器中提示語(yǔ)法錯(cuò)誤
    if(canvas.getcontext){
    //獲取對(duì)應(yīng)的canvasrenderingcontext2d對(duì)象(畫筆)
    var ctx = canvas.getcontext(2d);
    //線條的顏色
    ctx.strokestyle=#ff9933;
    //線條的寬度像素
    ctx.linewidth=10;
    //線條的兩關(guān)形狀
    ctx.linecap=round;
    //注意,canvas的坐標(biāo)系是:canvas畫布的左上角為原點(diǎn)(0,0),向右為橫坐標(biāo),向下為縱坐標(biāo),單位是像素(px)。
    //開始一個(gè)新的繪制路徑
    ctx.beginpath();
    //定義直線的起點(diǎn)坐標(biāo)為(10,10)
    ctx.moveto(50, 50);
    //定義直線的終點(diǎn)坐標(biāo)為(50,10)
    ctx.lineto(350, 250);
    ctx.moveto(50, 240);
    ctx.lineto(360, 60);
    ctx.moveto(50, 200);
    ctx.lineto(300, 40);
    //沿著坐標(biāo)點(diǎn)順序的路徑繪制直線
    ctx.stroke();
    //關(guān)閉當(dāng)前的繪制路徑
    ctx.closepath();
    }
    </script>
    </body>
    </html>