HTMLCanvasの基本
Webページにキャンバスを描画するには、HTML5キャンバス要素を使用します。
すべてのキャンバスには、キャンバスの高さと幅を表す2つの要素があります。つまり、それぞれ高さと幅です。
これに伴い、以下のコードスニペットに示すように、canvasのIDも設定する必要があります-
<canvas id = "newCanvas" width = "100" height = "100"></canvas>
getElementById()メソッドを使用してDOM内の
var canvas = document.getElementById("newCanvas"); キャンバスに何かを表示するには、スクリプトは最初にレンダリングコンテキストにアクセスし、そこに描画する必要があります。
を使用してHTML5でパスを描画する例を見てみましょう。
例
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
background-color: orange;
}
</style>
<script>
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> 出力
これにより、次の出力が生成されます-
HTML5で二次曲線を描く別の例を見てみましょう-
例
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type>
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キャンバスstroke()メソッド
HTMLキャンバスのstroke()メソッドを使用して、パスを描画します。このパスは、moveTo()およびlineTo()メソッドを使用して描画されます。 要素を使用すると、JavaScriptを使用してWebページにグラフィックを描画できます。すべてのキャンバスには、キャンバスの高さと幅を表す2つの要素があります。つまり、それぞれ高さと幅です。 以下は構文です- ctx.stroke() ここで、canvasのstroke()メソッドを実装する例を見てみましょう- 例 <!DOCTYPE html> <html> <body> <canvas
-
HTMLDOMキャンバスオブジェクト
HTML DOM Canvasオブジェクトは、HTML5で導入された要素に関連付けられています。 タグは、JavaScriptを使用してグラフィックを描画するために使用されます。キャンバスはグラフィックのコンテナとして機能します。キャンバスには、線や形などを描くことができます。 プロパティ 以下はCanvasObjectのプロパティです- プロパティ 説明 fillStyle 図面の塗りつぶしに使用される色、グラデーション、またはパターンを設定または返すため。 strokeStyle ストロークに使用される色、グラデーション、またはパターンを設定または返すため。