1. 程式人生 > 其它 >canvas基本用法(一)

canvas基本用法(一)

一、定義

<canvas>元素包含於HTML5中的,使用javaScript在網頁上繪製圖像

二、使用步驟

  1. 建立canvas元素,在HTML5頁面新增canvas元素
  2. 設定畫布寬度和高度
     <canvas id="tutorial" width="200" height="350"></canvas>
  3. 通過Javascript繪製
     state.canvas = document.getElementById('tutorial');//獲取元素的DOM物件
                state.context = state.canvas.getContext('2d');

三、基本使用

 state.canvas = document.getElementById('tutorial');//獲取元素的DOM物件
            state.context = state.canvas.getContext('2d');
            state.context.beginPath();//開始路徑繪圖
            state.context.moveTo(10,10);//起點
            state.context.lineTo(200,200)//畫直線
            state.context.stroke()//通過線條來繪製圖形輪廓。
 state.canvas = document.getElementById('tutorial');//獲取元素的DOM物件
            state.context = state.canvas.getContext('2d');
            state.context.beginPath();//開始路徑繪圖
            state.context.moveTo(10,10);//起點
            state.context.lineTo(200,200)//畫直線
            state.context.lineTo(100,200)//畫直線
            state.context.stroke()//
通過線條來繪製圖形輪廓。
 state.canvas = document.getElementById('tutorial');//獲取元素的DOM物件
            state.context = state.canvas.getContext('2d');
            state.context.beginPath();//開始路徑繪圖
            state.context.moveTo(10,10);//起點
            state.context.lineTo(200,200)//畫直線
            state.context.lineTo(100,200)//畫直線
            state.context.fill()//通過填充路徑的內容區域生成實心的圖形。
 state.canvas = document.getElementById('tutorial');//獲取元素的DOM物件
            state.context = state.canvas.getContext('2d');
            state.context.beginPath();
            state.context.arc(85, 85, 50, 0, Math.PI * 2, true); // 繪製
            // arc(x, y, radius, startAngle, endAngle, anticlockwise)
            // 畫一個以(x,y)為圓心的以radius為半徑的圓弧(圓),從startAngle開始到endAngle結束,按照anticlockwise給定的方向(預設為順時針)來生成。
 state.canvas = document.getElementById('tutorial');//獲取元素的DOM物件
            state.context = state.canvas.getContext('2d');
            state.context.beginPath();
            state.context.arc(75, 75, 50, 0, Math.PI * 2, true); // 繪製
            state.context.moveTo(110, 75);//將筆觸移動到指定的座標x以及y上。
            state.context.arc(75, 75, 35, 0, Math.PI, false);   // 口(順時針)
            state.context.moveTo(65, 65);
            state.context.arc(60, 65, 5, 0, Math.PI * 2, true);  // 左眼
            state.context.moveTo(65, 65);
            state.context.arc(90, 65, 5, 0, Math.PI * 2, true);  // 右眼
            state.context.stroke();