Html5-canvas-drawing-rectangles

提供:Dev Guides
移動先:案内検索

HTML5 Canvas-四角形の描画

キャンバスに長方形を描く3つの方法があります-

Sr.No. Method and Description
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>

上記のコードは、次の長方形を描画します-