HTML - 畫布



HTML 元素 <canvas> 提供了一種簡單而強大的方法,可以使用 JavaScript 繪製圖形。它可以用於繪製圖表、製作照片合成或製作簡單的(以及不太簡單的)動畫。

這是一個簡單的 <canvas> 元素,它只有兩個特定屬性 width 和 height,以及所有核心 HTML 屬性,如 id、name 和 class 等。

<canvas id="mycanvas" width="100" height="100"></canvas>

您可以使用 getElementById() 方法輕鬆地在 DOM 中找到 <canvas> 元素,如下所示:

var canvas  = document.getElementById("mycanvas");

示例

讓我們來看一個示例,該示例演示如何在 HTML 文件中使用 <canvas> 元素。

<!DOCTYPE html>
<html>
<head>
   <style>
      #mycanvas{border:1px solid red;}
   </style>
</head>
<body>
   <canvas id="mycanvas" width="100" height="100"></canvas>
</body>
</html>

渲染上下文

<canvas> 最初是空白的,要顯示某些內容,指令碼首先需要訪問渲染上下文。canvas 元素有一個名為 getContext 的 DOM 方法,用於獲取渲染上下文及其繪圖函式。此函式採用一個引數,即上下文型別 2d

例項

以下是獲取所需上下文以及檢查瀏覽器是否支援 <canvas> 元素的程式碼:

var canvas  = document.getElementById("mycanvas");
if (canvas.getContext){
   var ctx = canvas.getContext('2d');
   // drawing code here
} else {
   // canvas-unsupported code here
}

瀏覽器支援

最新版本的 Firefox、Safari、Chrome 和 Opera 都支援 HTML Canvas,但 IE8 本身不支援 canvas。

您可以使用 ExplorerCanvas 透過 Internet Explorer 獲得 canvas 支援。您只需要包含以下 JavaScript 程式碼:

<!--[if IE]><script src="excanvas.js"></script><![endif]-->

HTML Canvas - 繪製矩形

有三種方法可以在畫布上繪製矩形:

序號 方法和描述
1

fillRect(x,y,width,height)

此方法繪製一個填充的矩形。

2

strokeRect(x,y,width,height)

此方法繪製一個矩形輪廓。

3

clearRect(x,y,width,height)

此方法清除指定區域並使其完全透明

這裡 x 和 y 指定畫布上矩形左上角位置(相對於原點),width 和 height 是矩形的 寬度高度

示例

以下是一個簡單的示例,它使用上述方法繪製一個漂亮的矩形。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   
   <script type="text/javascript">
      function drawShape(){
         
         // Get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            // Draw shapes
            ctx.fillRect(25,25,100,100);
            ctx.clearRect(45,45,60,60);
            ctx.strokeRect(50,50,50,50);
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

HTML Canvas - 繪製路徑

我們需要以下方法在畫布上繪製路徑:

序號 方法和描述
1

beginPath()

此方法重置當前路徑。

2

moveTo(x, y)

此方法使用給定點建立一個新的子路徑。

3

closePath()

此方法將當前子路徑標記為已關閉,並使用與新關閉子路徑的起點和終點相同的點啟動新的子路徑。

4

fill()

此方法使用當前填充樣式填充子路徑。

5

stroke()

此方法使用當前筆觸樣式描邊子路徑。

6

arc(x, y, radius, startAngle, endAngle, anticlockwise)

向子路徑新增點,以便新增由引數描述的圓的周長所描述的弧,從給定的起始角度開始,到給定的結束角度結束,沿給定的方向移動,並透過直線連線到前一點。

示例

以下是一個簡單的示例,它使用上述方法繪製一個形狀。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            // Draw shapes
            ctx.beginPath();
            ctx.arc(75,75,50,0,Math.PI*2,true);  // Outer circle
            ctx.moveTo(110,75);
            ctx.arc(75,75,35,0,Math.PI,false);   // Mouth
            ctx.moveTo(65,65);
            ctx.arc(60,65,5,0,Math.PI*2,true);  // Left eye
            ctx.moveTo(95,65);
            ctx.arc(90,65,5,0,Math.PI*2,true);  // Right eye
            ctx.stroke();
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>	
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>	
</html>

HTML Canvas - 繪製線條

線條方法

我們需要以下方法在畫布上繪製線條:

序號 方法和描述
1

beginPath()

此方法重置當前路徑。

2

moveTo(x, y)

此方法使用給定點建立一個新的子路徑。

3

closePath()

此方法將當前子路徑標記為已關閉,並使用與新關閉子路徑的起點和終點相同的點啟動新的子路徑。

4

fill()

此方法使用當前填充樣式填充子路徑。

5

stroke()

此方法使用當前筆觸樣式描邊子路徑。

6

lineTo(x, y)

此方法將給定點新增到當前子路徑,並透過直線連線到前一個點。

示例

以下是一個簡單的示例,它使用上述方法繪製一個三角形。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            // Filled triangle
            ctx.beginPath();
            ctx.moveTo(25,25);
            ctx.lineTo(105,25);
            ctx.lineTo(25,105);
            ctx.fill();
            
            // Stroked triangle
            ctx.beginPath();
            ctx.moveTo(125,125);
            ctx.lineTo(125,45);
            ctx.lineTo(45,125);
            ctx.closePath();
            ctx.stroke();
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

HTML Canvas - 繪製貝塞爾曲線

我們需要以下方法在畫布上繪製貝塞爾曲線:

序號 方法和描述
1

beginPath()

此方法重置當前路徑。

2

moveTo(x, y)

此方法使用給定點建立一個新的子路徑。

3

closePath()

此方法將當前子路徑標記為已關閉,並使用與新關閉子路徑的起點和終點相同的點啟動新的子路徑。

4

fill()

此方法使用當前填充樣式填充子路徑。

5

stroke()

此方法使用當前筆觸樣式描邊子路徑。

6

bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

此方法將給定點新增到當前路徑,並透過具有給定控制點的三次貝塞爾曲線連線到前一個點。

bezierCurveTo() 方法中的 x 和 y 引數是端點的座標。cp1x 和 cp1y 是第一個控制點的座標,cp2x 和 cp2y 是第二個控制點的座標。

示例

以下是一個簡單的示例,它使用上述方法繪製貝塞爾曲線。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            ctx.beginPath();
            ctx.moveTo(75,40);
            ctx.bezierCurveTo(75,37,70,25,50,25);
            ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
            ctx.bezierCurveTo(20,80,40,102,75,120);
            ctx.bezierCurveTo(110,102,130,80,130,62.5);
            ctx.bezierCurveTo(130,62.5,130,25,100,25);
            ctx.bezierCurveTo(85,25,75,37,75,40);
            ctx.fill();
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

HTML Canvas - 繪製二次曲線

我們需要以下方法在畫布上繪製二次曲線:

序號 方法和描述
1

beginPath()

此方法重置當前路徑。

2

moveTo(x, y)

此方法使用給定點建立一個新的子路徑。

3

closePath()

此方法將當前子路徑標記為已關閉,並使用與新關閉子路徑的起點和終點相同的點啟動新的子路徑。

4

fill()

此方法使用當前填充樣式填充子路徑。

5

stroke()

此方法使用當前筆觸樣式描邊子路徑。

6

quadraticCurveTo(cpx, cpy, x, y)

此方法將給定點新增到當前路徑,並透過具有給定控制點的二次貝塞爾曲線連線到前一個點。

quadraticCurveTo() 方法中的 x 和 y 引數是端點的座標。cpxcpy 是控制點的座標。

示例

以下是一個簡單的示例,它使用上述方法繪製二次曲線。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            // Draw shapes
            ctx.beginPath();
            ctx.moveTo(75,25);
            ctx.quadraticCurveTo(25,25,25,62.5);
            ctx.quadraticCurveTo(25,100,50,100);
            ctx.quadraticCurveTo(50,120,30,125);
            ctx.quadraticCurveTo(60,120,65,100);
            ctx.quadraticCurveTo(125,100,125,62.5);
            ctx.quadraticCurveTo(125,25,75,25);
            ctx.stroke();
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

HTML Canvas - 使用影像

本教程將展示如何將外部影像匯入畫布,然後如何使用以下方法在該影像上繪製:

序號 方法和描述
1

beginPath()

此方法重置當前路徑。

2

moveTo(x, y)

此方法使用給定點建立一個新的子路徑。

3

closePath()

此方法將當前子路徑標記為已關閉,並使用與新關閉子路徑的起點和終點相同的點啟動新的子路徑。

4

fill()

此方法使用當前填充樣式填充子路徑。

5

stroke()

此方法使用當前筆觸樣式描邊子路徑。

6

drawImage(image, dx, dy)

此方法將給定影像繪製到畫布上。這裡 image 是對影像或畫布物件的引用。x 和 y 構成目標畫布上應放置影像的座標。

示例

以下是一個簡單的示例,它使用上述方法匯入影像。

<!DOCTYPE HTML>
<html>
<head>      
   <script type = "text/javascript">
      function drawShape() {
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext) {
         
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            // Draw shapes
            var img = new Image();
            img.src = '/html/images/backdrop.jpg';            
            img.onload = function() {
               ctx.drawImage(img,0,0);
               ctx.beginPath();
               
               ctx.moveTo(30,96);
               ctx.lineTo(70,66);
               
               ctx.lineTo(103,76);
               ctx.lineTo(170,15);
               
               ctx.stroke();
            }
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>   
<body onload = "drawShape();">
   <canvas id = "mycanvas"></canvas>
</body>  
</html>

HTML Canvas - 建立漸變

HTML canvas 允許我們使用以下方法使用線性漸變和徑向漸變填充和描邊形狀:

序號 方法和描述
1

addColorStop(offset, color)

此方法在給定偏移量的漸變中新增具有給定顏色的顏色停止點。這裡 0.0 是漸變一端的偏移量,1.0 是另一端的偏移量。

2

createLinearGradient(x0, y0, x1, y1)

此方法返回一個 CanvasGradient 物件,該物件表示一個線性漸變,沿著由引數表示的座標給出的線繪製。四個引數表示漸變的起點 (x1,y1) 和終點 (x2,y2)。

3

createRadialGradient(x0, y0, r0, x1, y1, r1)

此方法返回一個 CanvasGradient 物件,該物件表示一個徑向漸變,沿著由引數表示的圓錐體繪製。前三個引數定義一個具有座標 (x1,y1) 和半徑 r1 的圓,第二個引數定義一個具有座標 (x2,y2) 和半徑 r2 的圓。

示例 - 線性漸變

以下是一個簡單的示例,它使用上述方法建立線性漸變。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width:100px;
         height:100px;
         margin:0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            // Create Linear Gradients
            var lingrad = ctx.createLinearGradient(0,0,0,150);
            lingrad.addColorStop(0, '#00ABEB');
            lingrad.addColorStop(0.5, '#fff');
            lingrad.addColorStop(0.5, '#66CC00');
            lingrad.addColorStop(1, '#fff');
            var lingrad2 = ctx.createLinearGradient(0,50,0,95);
            lingrad2.addColorStop(0.5, '#000');
            lingrad2.addColorStop(1, 'rgba(0,0,0,0)');
            
            // assign gradients to fill and stroke styles
            ctx.fillStyle = lingrad;
            ctx.strokeStyle = lingrad2;
            
            // draw shapes
            ctx.fillRect(10,10,130,130);
            ctx.strokeRect(50,50,50,50);
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

示例 - 徑向漸變

以下是一個簡單的示例,它使用上述方法建立徑向漸變。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height: 100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape() {
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext) {
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            // Create gradients
            var radgrad = ctx.createRadialGradient(45, 45, 10, 52, 50, 30);
            radgrad.addColorStop(0, '#A7D30C');
            radgrad.addColorStop(0.9, '#019F62');
            radgrad.addColorStop(1, 'rgba(1,159,98,0)');
            
            var radgrad2 = ctx.createRadialGradient(105, 105, 20, 112, 120, 50);
            radgrad2.addColorStop(0, '#FF5F98');
            radgrad2.addColorStop(0.75, '#FF0188');
            radgrad2.addColorStop(1, 'rgba(255,1,136,0)');
            
            var radgrad3 = ctx.createRadialGradient(95, 15, 15, 102, 20, 40);
            radgrad3.addColorStop(0, '#00C9FF');
            radgrad3.addColorStop(0.8, '#00B5E2');
            radgrad3.addColorStop(1, 'rgba(0,201,255,0)');
            
            var radgrad4 = ctx.createRadialGradient(0, 150, 50, 0, 140, 90);
            radgrad4.addColorStop(0, '#F4F201');
            radgrad4.addColorStop(0.8, '#E4C700');
            radgrad4.addColorStop(1, 'rgba(228,199,0,0)');
            
            // draw shapes
            ctx.fillStyle = radgrad4;
            ctx.fillRect(0, 0, 150, 150);
            
            ctx.fillStyle = radgrad3;
            ctx.fillRect(0, 0, 150, 150);
            
            ctx.fillStyle = radgrad2;
            ctx.fillRect(0, 0, 150, 150);
            ctx.fillStyle = radgrad;
            ctx.fillRect(0, 0, 150, 150);
         } 
         else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

HTML Canvas - 樣式和顏色

HTML canvas 提供以下兩個重要屬性來將顏色應用於形狀:

序號 方法和描述
1

fillStyle

此屬性表示在形狀內部使用的顏色或樣式。

2

strokeStyle

此屬性表示用於形狀周圍線條的顏色或樣式

預設情況下,筆觸和填充顏色設定為黑色,即 CSS 顏色值 #000000。

示例 - fillStyle

以下是一個簡單的示例,它使用上述 fillStyle 屬性建立一個漂亮的圖案。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   
   <script type="text/javascript">
      function drawShape(){
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            // Create a pattern
            for (var i=0;i<7;i++){
               for (var j=0;j<7;j++){
                  ctx.fillStyle='rgb(' + Math.floor(255-20.5*i)+ ','+ Math.floor(255 - 42.5*j) + ',255)';
                  ctx.fillRect( j*25, i* 25, 55, 55 );
               }
            }
         } 
         else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

示例 - strokeStyle

以下是一個簡單的示例,它使用上述 fillStyle 屬性建立另一個漂亮的圖案。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            // Create a pattern
            for (var i=0;i<10;i++){
               for (var j=0;j<10;j++){
                  ctx.strokeStyle='rgb(255,'+ Math.floor(50-2.5*i)+','+ Math.floor(155 - 22.5 * j ) + ')';
                  ctx.beginPath();
                  ctx.arc(1.5+j*25, 1.5 + i*25,10,10,Math.PI*5.5, true);
                  ctx.stroke();
               }
            }
         } 
         else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

HTML Canvas - 文字和字型

HTML canvas 提供了使用不同字型和文字屬性建立文字的功能,如下所示:

序號 屬性和描述
1

font [ = value ]

此屬性返回當前字型設定,並且可以設定以更改字型。

2

textAlign [ = value ]

此屬性返回當前文字對齊設定,並且可以設定以更改對齊方式。可能的值為 start、end、left、right 和 center。

3

textBaseline [ = value ]

此屬性返回當前基線對齊設定,並且可以設定以更改基線對齊方式。可能的值為 top、hanging、middle、alphabetic、ideographic 和 bottom

4

fillText(text, x, y [, maxWidth ] )

此屬性填充給定座標 x 和 y 指定的給定位置的給定文字。

5

strokeText(text, x, y [, maxWidth ] )

此屬性描邊給定座標 x 和 y 指定的給定位置的給定文字。

示例

以下是一個簡單的示例,它使用上述屬性繪製文字:

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            ctx.fillStyle = '#00F';
            ctx.font = 'Italic 30px Sans-Serif';
            ctx.textBaseline = 'Top';
            ctx.fillText  ('Hello world!', 40, 100);
            ctx.font = 'Bold 30px Sans-Serif';
            ctx.strokeText('Hello world!', 40, 50);
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

HTML Canvas - 圖案和陰影

建立圖案

在畫布上建立圖案需要以下方法:

序號 方法和描述
1

createPattern(image, repetition)

此方法將使用影像建立圖案。第二個引數可以是一個字串,其值可以是以下之一:repeat、repeat-x、repeat-y 和 no-repeat。如果指定空字串或 null,則將假設為 repeat。

示例

下面是一個簡單的示例,它使用上述方法建立一個漂亮的圖案。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width:100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            // create new image object to use as pattern
            var img = new Image();
            img.src = '/html/images/pattern.jpg';
            img.onload = function(){
               
               // create pattern
               var ptrn = ctx.createPattern(img,'repeat');
               ctx.fillStyle = ptrn;
               ctx.fillRect(0,0,150,150);
            }
         } 
         else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

假設我們有以下圖案:

pattern

建立陰影

HTML canvas 提供了在圖形周圍建立漂亮陰影的功能。所有繪圖操作都受四個全域性陰影屬性的影響。

序號 屬性和描述
1

shadowColor [ = 值 ]

此屬性返回當前陰影顏色,並且可以設定以更改陰影顏色。

2

shadowOffsetX [ = 值 ]

此屬性返回當前陰影 X 偏移量,並且可以設定以更改陰影 X 偏移量。

3

shadowOffsetY [ = 值 ]

此屬性返回當前陰影 Y 偏移量,並且可以設定以更改陰影 Y 偏移量。

4

shadowBlur [ = 值 ]

此屬性返回應用於陰影的當前模糊級別,並且可以設定以更改模糊級別。

示例

下面是一個簡單的示例,它使用上述屬性來繪製陰影。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            ctx.shadowOffsetX = 2;
            ctx.shadowOffsetY = 2;
            ctx.shadowBlur = 2;
            ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
            ctx.font = "20px Times New Roman";
            ctx.fillStyle = "Black";
            ctx.fillText("This is shadow test", 5, 30);
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

HTML Canvas - 儲存和恢復狀態

HTML canvas 提供了兩種重要的儲存和恢復 canvas 狀態的方法。canvas 繪圖狀態基本上是所有已應用樣式和變換的快照,包括以下內容:

  • 諸如平移、旋轉和縮放等變換。

  • 當前剪下區域。

  • 以下屬性的當前值:strokeStyle、fillStyle、globalAlpha、lineWidth、lineCap、lineJoin、miterLimit、shadowOffsetX、shadowOffsetY、shadowBlur、shadowColor、globalCompositeOperation、font、textAlign、textBaseline。

每次呼叫 save 方法時,canvas 狀態都會儲存到堆疊中,並且每次呼叫 restore 方法時,都會從堆疊中返回最後儲存的狀態。

序號 方法和描述
1

save()

此方法將當前狀態壓入堆疊。

2

restore()

此方法彈出堆疊上的頂部狀態,將上下文恢復到該狀態。

示例

下面是一個簡單的示例,它使用上述方法來演示如何呼叫restore 來恢復原始狀態,最後一個矩形再次以黑色繪製。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            //  draw a rectangle with default settings
            ctx.fillRect(0,0,150,150);
            
            //  Save the default state
            ctx.save();
            // Make changes to the settings
            ctx.fillStyle = '#66FFFF'
            ctx.fillRect( 15,15,120,120);
            
            // Save the current state
            ctx.save();
            // Make the new changes to the settings
            ctx.fillStyle = '#993333'
            ctx.globalAlpha = 0.5;
            ctx.fillRect(30,30,90,90);
            // Restore previous state
            ctx.restore();
            
            // Draw a rectangle with restored settings
            ctx.fillRect(45,45,60,60);
            // Restore original state
            ctx.restore();
            
            // Draw a rectangle with restored settings
            ctx.fillRect(40,40,90,90);
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas"></canvas>
</body>
</html>

HTML Canvas - 平移

HTML canvas 提供了translate(x, y) 方法,該方法用於將 canvas 及其原點移動到網格中的不同點。

這裡引數 x 是 canvas 向左或向右移動的量,y 是其向上或向下移動的量。

示例

下面是一個簡單的示例,它使用上述方法來繪製各種螺旋線:

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width:100px;
         height:100px;
         margin:0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            ctx.fillRect(0,0,300,300);
            
            for (i=0;i<3;i++) {
               for (j=0;j<3;j++) {
                  ctx.save();
                  ctx.strokeStyle = "#FF0066";
                  ctx.translate(50+j*100,50+i*100);
                  drawSpirograph(ctx,10*(j+3)/(j+2),-2*(i+3)/(i+1),10);
                  ctx.restore();
               }
            }
         } 
         else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
      function drawSpirograph(ctx,R,r,O){
         var x1 = R-O;
         var y1 = 0;
         var i  = 1;
         ctx.beginPath();
         ctx.moveTo(x1,y1);
         do {
            if (i>20000) break;
               var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
               var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
               ctx.lineTo(x2,y2);
               x1 = x2;
               y1 = y2;
               i++;
         } while (x2 != R-O && y2 != 0 );
         ctx.stroke();
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas" width="400" height="400"></canvas>
</body>
</html>

HTML Canvas - 旋轉

HTML canvas 提供了rotate(angle) 方法,該方法用於圍繞當前原點旋轉 canvas。

此方法只接受一個引數,即 canvas 旋轉的角度。這是一個以弧度為單位測量的順時針旋轉。

示例

下面是一個簡單的示例,我們執行兩個迴圈,第一個迴圈確定環數,第二個迴圈確定每個環中繪製的點數。

<!DOCTYPE html>
<html>
<head>
   <style>
      #test {
         width: 100px;
         height:100px;
         margin: 0px auto;
      }
   </style>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            ctx.translate(100,100);
            for (i=1; i<7; i++){
               ctx.save();
               ctx.fillStyle = 'rgb('+(51*i)+','+(200-51*i)+',0)';
               for (j=0; j < i*6; j++){
                  ctx.rotate(Math.PI*2/(i*6));
                  ctx.beginPath();
                  ctx.arc(0,i*12.5,5,0,Math.PI*2,true);
                  ctx.fill();
               }
               ctx.restore();
            }
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body id="test" onload="drawShape();">
   <canvas id="mycanvas" width="400" height="400"></canvas>
</body>
</html>

HTML Canvas - 縮放

HTML canvas 提供了scale(x, y) 方法,該方法用於增加或減少 canvas 網格中的單位。這可以用於繪製縮小或放大的形狀和點陣圖。

此方法接受兩個引數,其中 x 是水平方向的縮放因子,y 是垂直方向的縮放因子。這兩個引數必須是正數。

小於 1.0 的值會減小單位大小,大於 1.0 的值會增加單位大小。將縮放因子精確設定為 1.0 不會影響單位大小。

示例

下面是一個簡單的示例,它使用螺旋線函式繪製具有不同縮放因子的九個形狀。

<!DOCTYPE html>
<html>
<head>
   <script type="text/javascript">
      function drawShape(){
         
         // Get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // Use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            ctx.strokeStyle = "#fc0";
            ctx.lineWidth = 1.5;
            ctx.fillRect(0,0,300,300);
            
            // Uniform scaling
            ctx.save()
            ctx.translate(50,50);
            drawSpirograph(ctx,22,6,5);
            ctx.translate(100,0);
            ctx.scale(0.75,0.75);
            drawSpirograph(ctx,22,6,5);
            ctx.translate(133.333,0);
            ctx.scale(0.75,0.75);
            drawSpirograph(ctx,22,6,5);
            ctx.restore();
            
            // Non uniform scaling (y direction)
            ctx.strokeStyle = "#0cf";
            ctx.save()
            ctx.translate(50,150);
            ctx.scale(1,0.75);
            drawSpirograph(ctx,22,6,5);
            ctx.translate(100,0);
            ctx.scale(1,0.75);
            drawSpirograph(ctx,22,6,5);
            ctx.translate(100,0);
            ctx.scale(1,0.75);
            drawSpirograph(ctx,22,6,5);
            ctx.restore();
            
            // Non uniform scaling (x direction)
            ctx.strokeStyle = "#cf0";
            ctx.save()
            ctx.translate(50,250);
            ctx.scale(0.75,1);
            drawSpirograph(ctx,22,6,5);
            ctx.translate(133.333,0);
            ctx.scale(0.75,1);
            drawSpirograph(ctx,22,6,5);
            ctx.translate(177.777,0);
            ctx.scale(0.75,1);
            drawSpirograph(ctx,22,6,5);
            ctx.restore();
         } else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
      function drawSpirograph(ctx,R,r,O){
         var x1 = R-O;
         var y1 = 0;
         var i  = 1;
         ctx.beginPath();
         ctx.moveTo(x1,y1);
         do {
            if (i>20000) break;
               var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
               var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
               ctx.lineTo(x2,y2);
               x1 = x2;
               y1 = y2;
               i++;
         }
         while (x2 != R-O && y2 != 0 );
            ctx.stroke();
      }
   </script>
</head>
<body onload="drawShape();">
   <canvas id="mycanvas" width="400" height="400"></canvas>
</body>
</html>

HTML Canvas - 變換

HTML canvas 提供了允許直接修改變換矩陣的方法。變換矩陣最初必須是單位變換。然後可以使用變換方法對其進行調整。

序號 方法和描述
1

transform(m11, m12, m21, m22, dx, dy)

此方法更改變換矩陣以應用引數給出的矩陣。

2

setTransform(m11, m12, m21, m22, dx, dy)

此方法將變換矩陣更改為引數給出的矩陣。

transform (m11, m12, m21, m22, dx, dy) 方法必須將當前變換矩陣與以下矩陣相乘:

m11     m21     dx
m12     m22     dy
0       0       1

setTransform(m11, m12, m21, m22, dx, dy) 方法必須將當前變換重置為單位矩陣,然後使用相同的引數呼叫transform(m11, m12, m21, m22, dx, dy) 方法。

示例

下面是一個簡單的示例,它使用 transform() 和 setTransform() 方法:

<!DOCTYPE html>
<html>
<head>
   <script type="text/javascript">
      function drawShape(){
         
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            var sin = Math.sin(Math.PI/6);
            var cos = Math.cos(Math.PI/6);
            
            ctx.translate(200, 200);
            var c = 0;
            
            for (var i=0; i <= 12; i++) {
               c = Math.floor(255 / 12 * i);
               ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
               ctx.fillRect(0, 0, 100, 100);
               ctx.transform(cos, sin, -sin, cos, 0, 0);
            }
            ctx.setTransform(-1, 0, 0, 1, 200, 200);
            ctx.fillStyle = "rgba(100, 100, 255, 0.5)";
            ctx.fillRect(50, 50, 100, 100);
         } 
         else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body onload="drawShape();">
   <canvas id="mycanvas" width="400" height="400"></canvas>
</body>
</html>

HTML Canvas - 合成

HTML canvas 提供了合成屬性globalCompositeOperation,它會影響所有繪圖操作。

我們可以使用 globalCompositeOperation 屬性在現有形狀後面繪製新形狀,遮蔽某些區域,從 canvas 中清除部分割槽域,如下例所示。

globalCompositeOperation 可以設定以下值:

序號 屬性和描述
1

source-over

這是預設設定,它在現有 canvas 內容的頂部繪製新形狀。

2

source-in

新形狀僅在新的形狀和目標 canvas 重疊的地方繪製。其他所有內容都將變為透明。

3

source-out

新形狀在它不與現有 canvas 內容重疊的地方繪製。

4

source-atop

新形狀僅在其與現有 canvas 內容重疊的地方繪製。

5

lighter

如果兩個形狀重疊,則顏色由新增顏色值確定。

6

xor

如果兩個形狀重疊,則形狀將變為透明,其他地方則正常繪製。

7

destination-over

新形狀繪製在現有 canvas 內容的後面。

8

destination-in

如果新的形狀和現有 canvas 內容重疊,則保留現有 canvas 內容。其他所有內容都將變為透明。

9

destination-out

如果現有內容不與新形狀重疊,則保留現有內容。

10

destination-atop

現有 canvas 僅在其與新形狀重疊的地方保留。新形狀繪製在 canvas 內容的後面。

11

darker

如果兩個形狀重疊,則顏色由減去顏色值確定。

示例

下面是一個簡單的示例,它使用 globalCompositeOperation 屬性建立所有可能的合成:

<!DOCTYPE html>
<html>
<head>
   <script type="text/javascript">
      var compositeTypes = [
         'source-over','source-in','source-out','source-atop',
         'destination-over','destination-in','destination-out',
         'destination-atop','lighter','darker','copy','xor'
      ];
      function drawShape(){
         for (i=0;i<compositeTypes.length;i++){
            var label = document.createTextNode(compositeTypes[i]);
            document.getElementById('lab'+i).appendChild(label);
            var ctx = document.getElementById('tut'+i).getContext('2d');
            
            // draw rectangle
            ctx.fillStyle = "#FF3366";
            ctx.fillRect(15,15,70,70);
            
            // set composite property
            ctx.globalCompositeOperation = compositeTypes[i];
            
            // draw circle
            ctx.fillStyle = "#0066FF";
            ctx.beginPath();
            ctx.arc(75,75,35,0,Math.PI*2,true);
            ctx.fill();
         }
      }
   </script>
</head>
<body onload="drawShape();">
   <table border="1" align="center">
      
      <tr>
         <td><canvas id="tut0" width="125" height="125"></canvas><br/>
            <label id="lab0"></label>
         </td>         
         <td><canvas id="tut1" width="125" height="125"></canvas><br/>
            <label id="lab1"></label>
         </td>         
         <td><canvas id="tut2" width="125" height="125"></canvas><br/>
            <label id="lab2"></label>
         </td>
      </tr>
      
      <tr>
         <td><canvas id="tut3" width="125" height="125"></canvas><br/>
            <label id="lab3"></label>
         </td>
         
         <td><canvas id="tut4" width="125" height="125"></canvas><br/>
            <label id="lab4"></label>
         </td>
         <td><canvas id="tut5" width="125" height="125"></canvas><br/>
            <label id="lab5"></label>
         </td>
      </tr>
      
      <tr>
         <td><canvas id="tut6" width="125" height="125"></canvas><br/>
            <label id="lab6"></label>
         </td>
         <td><canvas id="tut7" width="125" height="125"></canvas><br/>
            <label id="lab7"></label>
         </td>
         <td><canvas id="tut8" width="125" height="125"></canvas><br/>
            <label id="lab8"></label>
         </td>
      </tr>
      
      <tr>
         <td><canvas id="tut9" width="125" height="125"></canvas><br/>
            <label id="lab9"></label>
         </td>
         <td><canvas id="tut10" width="125" height="125"></canvas><br/>
            <label id="lab10"></label>
         </td>
         <td><canvas id="tut11" width="125" height="125"></canvas><br/>
            <label id="lab11"></label>
         </td>
      </tr>
   </table>
</body>
</html>

HTML Canvas - 動畫

HTML canvas 提供了繪製圖像並將其完全擦除的必要方法。我們可以藉助 Javascript 在 HTML canvas 上模擬良好的動畫。

以下是用於在 canvas 上製作影像動畫的兩種重要的 Javascript 方法:

序號 方法和描述
1

setInterval(callback, time);

此方法在給定的 time 毫秒後重復執行提供的程式碼。

2

setTimeout(callback, time);

此方法僅在給定的 time 毫秒後執行一次提供的程式碼。

示例

下面是一個簡單的示例,它將重複旋轉一個小影像:

<!DOCTYPE html>
<html>
<head>
   <script type="text/javascript">
      var pattern= new Image();
      function animate(){
         pattern.src = '/html/images/pattern.jpg';
         setInterval(drawShape, 100);
      }
      function drawShape(){
         // get the canvas element using the DOM
         var canvas = document.getElementById('mycanvas');
         
         // Make sure we don't execute when canvas isn't supported
         if (canvas.getContext){
            
            // use getContext to use the canvas for drawing
            var ctx = canvas.getContext('2d');
            
            ctx.fillStyle = 'rgba(0,0,0,0.4)';
            ctx.strokeStyle = 'rgba(0,153,255,0.4)';
            ctx.save();
            ctx.translate(150,150);
            
            var time = new Date();
            ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ( (2*Math.PI)/6000)*time.getMilliseconds() );
            ctx.translate(0,28.5);
            ctx.drawImage(pattern,-3.5,-3.5);
            ctx.restore();
         } 
         else {
            alert('You need Safari or Firefox 1.5+ to see this demo.');
         }
      }
   </script>
</head>
<body onload="animate();">
   <canvas id="mycanvas" width="400" height="400"></canvas>
</body>
</html>
廣告