canvas淺嘗

簡單了解canvas

1.什么是canvas

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

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

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

瀏覽器兼容

注:canvas不是矢量圖

2.canvas的作用

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

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

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

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

1.只用一個 Canvas DOM 元素,降低 DOM 數(shù)量與渲染的復(fù)雜度,可以將原來 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設(shè)置,但是不建議,因為如果之前設(shè)置了標(biāo)簽樣式,再設(shè)置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.如何看到畫

除非你在畫布上設(shè)置了內(nèi)容,否則你是看不見它的,會默認(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.在畫布上繪圖

將畫布放置在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');
            //開始在畫布繪制之前,我們必須遵循這個協(xié)議
            var context = canvas.getContext('2d');//提供一個可繪制的上下文
            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>

我們打算畫一個隨機生成的圓餅
建立一個表單去控制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,會不認(rèn)識canvas標(biāo)簽,會直接識別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做計算

創(chuàng)建一個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.奇怪的繪制

畫一個簡單的三角形

    context.beginPath();//開始
    context.moveTo(100, 150);////第一次的moveTo指的是將畫筆落到指定的位置
    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ù)是來確定圓心在畫布上的位置

radius用來指定圓的半徑

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

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

注意:角可以按負(fù)方向(從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°(注意:如果是按照負(fù)值或者逆時針方向來度量,那么終止角就是-90°)

10.度與弧度

360度 = 2PI弧度

11.再來編寫圓代碼
            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('在畫布上不知道寫什么...呵呵', 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,會不認(rèn)識canvas標(biāo)簽,會直接識別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)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容