canvas淺嘗

簡單了解canvas

1.什么是canvas

HTML5 的 canvas 元素使用 JavaScript 在網頁上繪制圖像。
畫布是一個矩形區域,您可以控制其每一像素。

canvas 擁有多種繪制路徑、矩形、圓形、字符以及添加圖像的方法。

版本支持:IE9以上
如果實在需要在IE9以前使用,可以查看 Exprorer Canvas Project和其他類似項目,通過插件來實現

瀏覽器兼容

注:canvas不是矢量圖

2.canvas的作用

一些可能的用途,包括使用Canvas構造圖形,動畫,游戲和圖片

當然也包括熱工藝圖。

3.我們為什么要使用canvas

性能,酷炫,還有什么好說的

1.只用一個 Canvas DOM 元素,降低 DOM 數量與渲染的復雜度,可以將原來 CPU 密集型變成 GPU 操作。
2.充分利用硬件資源的能力。
3.Canvas畫布無論是 JavaScript & H5,還是native都有類似的 API。因此我可以把瀏覽器Canvas接口的反射到用native畫布上,以此提高性能。

canvas初識

1.在web頁面增加畫布

在html頁面中增加
<canvas id="hehe" width="600" height="200"></canvas>
注意:canvas寬高可以通過css設置,但是不建議,因為如果之前設置了標簽樣式,再設置css樣式會把canvas圖像扯變形

例如:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>JS Bin</title>
        <style>
          #hehe{
            background:#000;
              width:400px;
              height:300px;
          }
        </style>

      </head>
      <body>
        <canvas id="hehe" width="300" height='300'></canvas>
      </body>
      <script>
        let canvas = document.getElementById("hehe"),
             ctx = canvas.getContext("2d");

        ctx.fillStyle = "green";
        ctx.fillRect(10, 10, 100, 100);
      </script>
    </html>
扯變形
2.如何看到畫

除非你在畫布上設置了內容,否則你是看不見它的,會默認為透明色

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>JS Bin</title>
        <style>
          #hehe{
            background:#000
          }
        </style>
      </head>
      <body>
        <canvas id="hehe" width="200" height='300'></canvas>
      </body>
    </html>
3.在畫布上繪圖

將畫布放置在x=10,y=10的位置建立一個寬高100的矩形

Paste_Image.png
4.一個小小的畫布測試
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>JS Bin</title>
        <style>
          #hehe{
            border:1px solid #000
          }
        </style>
        <script>
          window.onload = function(){
            var canvas = document.getElementById('hehe');
            //開始在畫布繪制之前,我們必須遵循這個協議
            var context = canvas.getContext('2d');//提供一個可繪制的上下文
            context.fillStyle = 'blue';//默認填充色為黑色,改變默認填充色
            context.fillRect(10, 10, 100, 100); //x, y, 寬, 高
            //如果只想要輪廓context.strokeRect(10, 10, 100, 100)
          }
        </script>
      </head>
      <body>
        <canvas id="hehe" width="300" height:'300'></canvas>
      </body>
    </html>

我們打算畫一個隨機生成的圓餅
建立一個表單去控制canvas輸出的圖像
準備工作
MDN canvas API
https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API
http://dev.w3.org/html5/2dcontext/

1.首先,建立HTML
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>JS Bin</title>
        <style>
          #hehe{
            border:1px solid #000
          }
        </style>
        <script></script>
      </head>
      <body>
        <canvas id="hehe" width="300" height:'300'>
        如果你的瀏覽器不支持canvas,會不認識canvas標簽,會直接識別canvas閉合標簽內的文本元素
        </canvas>
        <form>
          
        </form>
      </body>
    </html>
2.然后增加form
        <form>
          <p>
            <label for="backgroundColor">選擇背景顏色</laberl>
            <select id="backgroundColor">
              <option value="white" selected="selected">白色</option>
              <option value="black">黑色</option>
            </select>
          </p>
          <p>
            <label for="shape">選擇形狀</laberl>
            <select id="shape">
              <option value="none" selected="selected">都不</option>
              <option value="circles">圓</option>
              <option value="squares">方塊</option>
            </select>
          </p>
          <p>
            <label for="foregroundColor">選擇文本顏色</laberl>
            <select id="foregroundColor">
              <option value="black" selected="selected">黑色</option>
              <option value="white">白色</option>
            </select>
          </p>
          <p>
            <input type="button" id="previewButton" value="預覽">
          </p>
        </form>
3.用js做計算

創建一個hehe.js文件

          window.onload = function() {
            var button = document.getElementById('previewButton')
            button.onclick = previewHandler;
          }
          function previewHandler() {
            var canvas = document.getElementById('hehe');
            var context = canvas.getContext('2d');

            var selectObj = document.getElementById('shape');
            var index = selectObj.selectedIndex;
            var shape = selectObj[index].value;
            if(shape === "squares"){
              for(var squares = 0; squares < 20; squares++){
                drawSquare(canvas, context)
              }
            }
          }
4.編寫drawSquare函數
          function drawSquare(canvas, context){
            var w = Math.floor(Math.random() * 40);

            var x = Math.floor(Math.random() * canvas.width);

            var y = Math.floor(Math.random() * canvas.height);

            context.fillStyle = 'lightblue'
            context.fillRect(x, y, w, w)
          }
5.試試效果
6.增加backgroundColor調用
          function fillBackgroundColor(canvas, context){
            var selectObj = document.getElementById('backgroundColor');
            
            var index = selectObj.selectedIndex;
            
            var bgColor = selectObj.options[index].value
            
            context.fillStyle = bgColor;
            context.fillRect(0, 0, canvas.width, canvas.height)
          }
7.奇怪的繪制

畫一個簡單的三角形

    context.beginPath();//開始
    context.moveTo(100, 150);////第一次的moveTo指的是將畫筆落到指定的位置
    context.lineTo(250,75)
    context.lineTo(125,30)
    context.closePath();//結束
    context.stroke();//描繪
   //context.fillStyle='red'
   //context.fill();
8.分解arc
圓的方法:

context.arc(x, y, radius, startAngle, endAngle, direction)

x和y 參數是來確定圓心在畫布上的位置

radius用來指定圓的半徑

direction指定圓弧是逆時針還是順時針,布爾值,true為逆時針,false為順時針

startAngle 和 endAngle 是圓弧的起始角和 終止角

注意:角可以按負方向(從X軸逆時針)度量,也可以按正方向(從X軸順時針)度量

9.淺嘗弧線的使用
context.beginPath();
context.arc(70,70,60,0, (270 * Math.PI)/180, true)
//等于context.arc(70,70,60,0, (-90 *  Math.PI)/180, true)
context.stroke()

起始角X軸與弧線終點之間的角,由于我們的弧是一個90°的弧,所以終止角為270°(注意:如果是按照負值或者逆時針方向來度量,那么終止角就是-90°)

10.度與弧度

360度 = 2PI弧度

11.再來編寫圓代碼
            if(shape === "circles"){
              for(var circle = 0; circle < 20; circle++){
                drawCircle(canvas, context)
              }
            }
12.編寫drawCircle函數
          function drawCircle(canvas, context){
            var radius = Math.floor(Math.random() * 40);
            var x = Math.floor(Math.random() * canvas.width);
            var y = Math.floor(Math.random() * canvas.height);
            context.beginPath();
            context.arc(x, y, radius, 0 , 2 * Math.PI, true);
            context.fillStyle = 'lightblue'
            context.fill();
            context.stroke()
          }
13.完成drawText函數
          function drawText(canvas, context){
            var selectObj = document.getElementById('foregroundColor');
            var index = selectObj.selectedIndex;
            var fgColor = selectObj[index].value;
            
            context.fillStyle = fgColor;
            context.font = 'bold 1em sans-serif'
            context.textAligh = 'left'
            context.fillText('在畫布上不知道寫什么...呵呵', 20, 40)
          }
14.搞定
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    <style>
      #hehe{
        border:1px solid #000
      }
    </style>
    <script>
      window.onload = function() {
        var button = document.getElementById('previewButton')
        button.onclick = previewHandler;
      }
      function previewHandler() {
        var canvas = document.getElementById('hehe');
        var context = canvas.getContext('2d');
        fillBackgroundColor(canvas, context);
        drawText(canvas, context);
        var selectObj = document.getElementById('shape');
        var index = selectObj.selectedIndex;
        var shape = selectObj[index].value;
        if(shape === "squares"){
          for(var squares = 0; squares < 20; squares++){
            drawSquare(canvas, context)
          }
        }
        if(shape === "circles"){
          for(var circle = 0; circle < 20; circle++){
            drawCircle(canvas, context)
          }
        }
      }
      function drawSquare(canvas, context){
        var w = Math.floor(Math.random() * 40);

        var x = Math.floor(Math.random() * canvas.width);

        var y = Math.floor(Math.random() * canvas.height);

        context.fillStyle = 'lightblue'
        context.fillRect(x, y, w, w)
      }
      function fillBackgroundColor(canvas, context){
        var selectObj = document.getElementById('backgroundColor');

        var index = selectObj.selectedIndex;

        var bgColor = selectObj.options[index].value

        context.fillStyle = bgColor;
        context.fillRect(0, 0, canvas.width, canvas.height)
      }
      function drawCircle(canvas, context){
        var radius = Math.floor(Math.random() * 40);
        var x = Math.floor(Math.random() * canvas.width);
        var y = Math.floor(Math.random() * canvas.height);
        context.beginPath();
        context.arc(x, y, radius, 0 , 2 * Math.PI, true);
        context.fillStyle = 'lightblue'
        context.fill();
        context.stroke()
      }
      function drawText(canvas, context){
        var selectObj = document.getElementById('foregroundColor');
        var index = selectObj.selectedIndex;
        var fgColor = selectObj[index].value;

        context.fillStyle = fgColor;
        context.font = 'bold 1em sans-serif'
        context.textAligh = 'left'
        context.fillText('在畫布上不知道寫什么...呵呵', 20, 40)
      }
    </script>
  </head>
  <body>
    <canvas id="hehe" width="300" height:'300'>
    如果你的瀏覽器不支持canvas,會不認識canvas標簽,會直接識別canvas閉合標簽內的文本元素
    </canvas>
    <form>
      <p>
        <label for="backgroundColor">選擇背景顏色</laberl>
        <select id="backgroundColor">
          <option value="white" selected="selected">白色</option>
          <option value="black">黑色</option>
        </select>
      </p>
      <p>
        <label for="shape">選擇形狀</laberl>
        <select id="shape">
          <option value="none" selected="selected">都不</option>
          <option value="circles">圓</option>
          <option value="squares">方塊</option>
        </select>
      </p>
      <p>
        <label for="foregroundColor">選擇文本顏色</laberl>
        <select id="foregroundColor">
          <option value="black" selected="selected">黑色</option>
          <option value="white">白色</option>
        </select>
      </p>
      <p>
        <input type="button" id="previewButton" value="預覽">
      </p>
    </form>
  </body>
</html>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,818評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,185評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,656評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,647評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,446評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,951評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,041評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,189評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,718評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,602評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,800評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,316評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,045評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,419評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,671評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,420評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,755評論 2 371

推薦閱讀更多精彩內容

  • 一:canvas簡介 1.1什么是canvas? ①:canvas是HTML5提供的一種新標簽 ②:HTML5 ...
    GreenHand1閱讀 4,702評論 2 32
  • 版權聲明:本文為博主原創文章,未經博主允許不得轉載 前言 Canvas 本意是畫布的意思,然而將它理解為繪制工具一...
    cc榮宣閱讀 41,599評論 1 47
  • 一、簡介 HTML5 中的定義:“它是依賴分辨率的位圖畫布,你可以在 canvas 上面繪制任何圖形,甚至加載照片...
    destiny0904閱讀 10,564評論 1 4
  • 本文首發于我的個人博客:http://cherryblog.site/github項目地址:https://git...
    sunshine小小倩閱讀 2,005評論 1 8
  • 一、canvas簡介 1.1 什么是canvas?(了解) 是HTML5提供的一種新標簽 Canvas是一個矩形區...
    Looog閱讀 3,943評論 3 40