WebGL (1)


Canvas

HTML5ではcanvasタグが追加され、JavaScriptからWebページ内にいろいろな図形を描画できる ようになりました。

JavaScriptの例4

js_sample04.html
<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <script src="DrawTriangle.js" type="text/javascript"></script>
  <script language="JavaScript" type="text/javascript">
    //<![CDATA
function main() {
    var canvas = document.getElementById("mycanvas");
    drawFig(canvas);
}
//]]>
  </script>
</head>
<body onload="main()">
  <canvas id="mycanvas" width="320" height="240">
    Your browser does not support Canvas TAB.
  </canvas>
</body>
</html>
DrawTriangle.js
function drawFig(canvas) {
    if (!canvas || !canvas.getContext) {
	console.log("canvas not supported");
	return;
    }
    
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(20, 10);
    ctx.lineTo(300, 120);
    ctx.lineTo(100, 200);
    ctx.closePath();
    ctx.fillStyle = 'rgba(0, 255, 0, 1.0)';
    ctx.fill();

    ctx.beginPath();
    ctx.moveTo(100,100);
    ctx.lineTo(250,10);
    ctx.lineTo(200,200);
    ctx.closePath();
    ctx.strokeStyle = 'rgba(255, 0, 0, 1.0)';
    ctx.stroke();
}

JavaScriptの例5

マウスのクリックを処理することができます。
js_sample05.html
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <script language="JavaScript" type="text/javascript">
    //<![CDATA
var ctx;
function main() {
    var canvas = document.getElementById("mycanvas");
    if (!canvas || !canvas.getContext) {
	console.log("canvas not supported");
	return;
    }
    ctx = canvas.getContext('2d');
    canvas.onmousedown = myClick;
    ctx.fillStyle = "rgba(0,255,0,1.0)";
    ctx.fillRect(0,0,canvas.width,canvas.height);
    ctx.fillStyle = "rgba(0,0,0,1.0)";
}
function myClick(ev) {
    var rect = ev.target.getBoundingClientRect();
    var x = ev.clientX - rect.left;
    var y = ev.clientY - rect.top;
    ctx.fillRect(x,y,10,10);
    console.log("mouse x="+x+" y="+y);
}
//]]>
  </script>
</head>
<body onload="main()">
  <canvas id="mycanvas" width="320" height="240">
    Your browser does not support Canvas TAB.
  </canvas>
</body>
</html>