canvasの使い方

canvasの作成

htmlに<canvas></canvas>を記述し、id、横幅(width)、高さ(height)を指定します。

<canvas id="test" width=480" height="320"></canvas>

コンテキストの取得

キャンバスの操作は、コンテキストに対して行ないます。

var ctx = document.getElementById("test").getContext("2d") ;

色の指定方法

色の指定は、cssと同じ16進数での指定、rgbでの指定(0~255)。
αを使うならrgbaで指定(透明度のαは0~1.0)。

ctx.fillStyle = "#4080c0" ;
ctx.fillStyle = "rgb(64,128,192)" ;
ctx.fillStyle = "rgba(64,128,192,0.5)" ;

ボックスの塗りつぶし

事前にfillStyleで色を指定しておきます。

ctx.fillRect(始点X,始点Y,横幅,高さ) ;
ctx.fillRect(0,0,320,240) ;

多角形の描画

beginPathでパスを開始し、moveToで始点を指定しlineToでパスを繋いで行き、closePathで閉じる。
塗りつぶしはfillで行います。輪郭(パス)の描画ならstrokeを使います。(closePathは省略可能)

ctx.beginPath() ;                       // パスの開始
ctx.moveTo(160,20) ;                    // ペンを移動
ctx.lineTo(300,220) ;                   // ラインを引く
ctx.lineTo( 20,220) ;
ctx.closePath() ;                       // パスの終了

ctx.fillStyle = "rgba(0,0,255,0.5)" ;   // 色指定
ctx.fill() ;                            // パスを使って塗りつぶし

ctx.fillStyle = "#000" ;                // 色指定
ctx.lineWidth = 8 ;                     // 線の太さ
ctx.stroke() ;                          // 輪郭の描画

web/canvasの使い方.txt · 最終更新: 2018/03/18 09:56 (外部編集)
 
特に明示されていない限り、本Wikiの内容は次のライセンスに従います: CC Attribution-Share Alike 4.0 International
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki