canvas淺嘗

簡(jiǎn)單了解canvas

1.什么是canvas

HTML5 的 canvas 元素使用 JavaScript 在網(wǎng)頁(yè)上繪制圖像维咸。
畫(huà)布是一個(gè)矩形區(qū)域,您可以控制其每一像素周荐。

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

版本支持:IE9以上
如果實(shí)在需要在IE9以前使用鸭廷,可以查看 Exprorer Canvas Project和其他類似項(xiàng)目枣抱,通過(guò)插件來(lái)實(shí)現(xiàn)

瀏覽器兼容

注:canvas不是矢量圖

2.canvas的作用

一些可能的用途,包括使用Canvas構(gòu)造圖形辆床,動(dòng)畫(huà)佳晶,游戲和圖片

當(dāng)然也包括熱工藝圖。

3.我們?yōu)槭裁匆褂胏anvas

性能讼载,酷炫轿秧,還有什么好說(shuō)的

1.只用一個(gè) Canvas DOM 元素,降低 DOM 數(shù)量與渲染的復(fù)雜度咨堤,可以將原來(lái) CPU 密集型變成 GPU 操作菇篡。
2.充分利用硬件資源的能力。
3.Canvas畫(huà)布無(wú)論是 JavaScript & H5一喘,還是native都有類似的 API驱还。因此我可以把瀏覽器Canvas接口的反射到用native畫(huà)布上,以此提高性能凸克。

canvas初識(shí)

1.在web頁(yè)面增加畫(huà)布

在html頁(yè)面中增加
<canvas id="hehe" width="600" height="200"></canvas>
注意:canvas寬高可以通過(guò)css設(shè)置议蟆,但是不建議,因?yàn)槿绻霸O(shè)置了標(biāo)簽樣式萎战,再設(shè)置css樣式會(huì)把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.如何看到畫(huà)

除非你在畫(huà)布上設(shè)置了內(nèi)容咐容,否則你是看不見(jiàn)它的,會(huì)默認(rèn)為透明色

    <!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.在畫(huà)布上繪圖

將畫(huà)布放置在x=10,y=10的位置建立一個(gè)寬高100的矩形

Paste_Image.png
4.一個(gè)小小的畫(huà)布測(cè)試
    <!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');
            //開(kāi)始在畫(huà)布繪制之前蚂维,我們必須遵循這個(gè)協(xié)議
            var context = canvas.getContext('2d');//提供一個(gè)可繪制的上下文
            context.fillStyle = 'blue';//默認(rèn)填充色為黑色戳粒,改變默認(rèn)填充色
            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>

我們打算畫(huà)一個(gè)隨機(jī)生成的圓餅
建立一個(gè)表單去控制canvas輸出的圖像
準(zhǔn)備工作
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鸟雏,會(huì)不認(rèn)識(shí)canvas標(biāo)簽享郊,會(huì)直接識(shí)別canvas閉合標(biāo)簽內(nèi)的文本元素
        </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="預(yù)覽">
          </p>
        </form>
3.用js做計(jì)算

創(chuàng)建一個(gè)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函數(shù)
          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調(diào)用
          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.奇怪的繪制

畫(huà)一個(gè)簡(jiǎn)單的三角形

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

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

x和y 參數(shù)是來(lái)確定圓心在畫(huà)布上的位置

radius用來(lái)指定圓的半徑

direction指定圓弧是逆時(shí)針還是順時(shí)針,布爾值孝鹊,true為逆時(shí)針炊琉,false為順時(shí)針

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

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

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軸與弧線終點(diǎn)之間的角又活,由于我們的弧是一個(gè)90°的弧苔咪,所以終止角為270°(注意:如果是按照負(fù)值或者逆時(shí)針?lè)较騺?lái)度量,那么終止角就是-90°)

10.度與弧度

360度 = 2PI弧度

11.再來(lái)編寫圓代碼
            if(shape === "circles"){
              for(var circle = 0; circle < 20; circle++){
                drawCircle(canvas, context)
              }
            }
12.編寫drawCircle函數(shù)
          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函數(shù)
          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('在畫(huà)布上不知道寫什么...呵呵', 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('在畫(huà)布上不知道寫什么...呵呵', 20, 40)
      }
    </script>
  </head>
  <body>
    <canvas id="hehe" width="300" height:'300'>
    如果你的瀏覽器不支持canvas柳骄,會(huì)不認(rèn)識(shí)canvas標(biāo)簽团赏,會(huì)直接識(shí)別canvas閉合標(biāo)簽內(nèi)的文本元素
    </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="預(yù)覽">
      </p>
    </form>
  </body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市耐薯,隨后出現(xiàn)的幾起案子舔清,更是在濱河造成了極大的恐慌丝里,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,084評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件体谒,死亡現(xiàn)場(chǎng)離奇詭異杯聚,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)抒痒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門幌绍,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人故响,你說(shuō)我怎么就攤上這事傀广。” “怎么了彩届?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,450評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵伪冰,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我樟蠕,道長(zhǎng)糜值,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,322評(píng)論 1 293
  • 正文 為了忘掉前任坯墨,我火速辦了婚禮寂汇,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘捣染。我一直安慰自己骄瓣,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,370評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布耍攘。 她就那樣靜靜地躺著榕栏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蕾各。 梳的紋絲不亂的頭發(fā)上扒磁,一...
    開(kāi)封第一講書(shū)人閱讀 51,274評(píng)論 1 300
  • 那天,我揣著相機(jī)與錄音式曲,去河邊找鬼妨托。 笑死,一個(gè)胖子當(dāng)著我的面吹牛吝羞,可吹牛的內(nèi)容都是我干的兰伤。 我是一名探鬼主播,決...
    沈念sama閱讀 40,126評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼钧排,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼敦腔!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起恨溜,我...
    開(kāi)封第一講書(shū)人閱讀 38,980評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤符衔,失蹤者是張志新(化名)和其女友劉穎找前,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體判族,經(jīng)...
    沈念sama閱讀 45,414評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡纸厉,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,599評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了五嫂。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,773評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡肯尺,死狀恐怖沃缘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情则吟,我是刑警寧澤槐臀,帶...
    沈念sama閱讀 35,470評(píng)論 5 344
  • 正文 年R本政府宣布,位于F島的核電站氓仲,受9級(jí)特大地震影響水慨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜敬扛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,080評(píng)論 3 327
  • 文/蒙蒙 一晰洒、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧啥箭,春花似錦谍珊、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,713評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至坏怪,卻和暖如春贝润,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背铝宵。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,852評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工打掘, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人鹏秋。 一個(gè)月前我還...
    沈念sama閱讀 47,865評(píng)論 2 370
  • 正文 我出身青樓胧卤,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親拼岳。 傳聞我的和親對(duì)象是個(gè)殘疾皇子枝誊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,689評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 一:canvas簡(jiǎn)介 1.1什么是canvas? ①:canvas是HTML5提供的一種新標(biāo)簽 ②:HTML5 ...
    GreenHand1閱讀 4,681評(píng)論 2 32
  • 版權(quán)聲明:本文為博主原創(chuàng)文章惜纸,未經(jīng)博主允許不得轉(zhuǎn)載 前言 Canvas 本意是畫(huà)布的意思,然而將它理解為繪制工具一...
    cc榮宣閱讀 41,561評(píng)論 1 47
  • 一叶撒、簡(jiǎn)介 HTML5 中的定義:“它是依賴分辨率的位圖畫(huà)布绝骚,你可以在 canvas 上面繪制任何圖形,甚至加載照片...
    destiny0904閱讀 10,537評(píng)論 1 4
  • 本文首發(fā)于我的個(gè)人博客:http://cherryblog.site/github項(xiàng)目地址:https://git...
    sunshine小小倩閱讀 1,983評(píng)論 1 8
  • 一祠够、canvas簡(jiǎn)介 1.1 什么是canvas压汪?(了解) 是HTML5提供的一種新標(biāo)簽 Canvas是一個(gè)矩形區(qū)...
    Looog閱讀 3,942評(píng)論 3 40