JavaScript (HTML5): 図形を描画

snippet-canvas.js

javascript: snippet-canvas.js

(function() {
	function SnippetCanvas() {
		this.canvas = document.createElement("canvas");
		this.canvas.width = 500;
		this.canvas.height = 400;
		this.context = this.canvas.getContext("2d");
		this.context.translate(0.5, 0.5);
		document.body.appendChild(this.canvas);
	};
	SnippetCanvas.prototype.drawGrid = function() {
		this.context.beginPath();
		this.context.lineWidth = 1;
		this.context.strokeStyle = "rgb(200, 200, 255)";
		for (var x = 50; x < this.canvas.width; x+=50) {
			this.context.moveTo(x, 0);
			this.context.lineTo(x, this.canvas.height);
		}
		for (var y = 50; y < this.canvas.height; y+=50) {
			this.context.moveTo(0, y);
			this.context.lineTo(this.canvas.width, y);
		}
		this.context.closePath();
		this.context.stroke();
	};
	SnippetCanvas.prototype.drawRect = function() {
		this.context.fillStyle = "rgb(255, 0, 0)";
		this.context.rect(50,50,100,100);
		this.context.fill();
	};
	SnippetCanvas.prototype.drawCircle = function() {
		this.context.fillStyle = "rgb(255, 0, 255)";
		this.context.beginPath();
		this.context.arc(300,200,100,0/180*Math.PI,360/180*Math.PI,true);
		this.context.closePath();
		this.context.fill();
	};
	SnippetCanvas.prototype.drawPolygon = function() {
		this.context.fillStyle = "rgb(255, 255, 0)";
		this.context.beginPath();
		this.context.moveTo(100,200);
		this.context.lineTo(150,300);
		this.context.lineTo( 50,300);
		this.context.closePath();
		this.context.fill();
	};
	SnippetCanvas.prototype.drawText = function() {
		this.context.fillStyle = "red";
		this.context.font = "30px 'Times New Roman'";
		this.context.textAlign = "left";
		this.context.textBaseline = "top";
		this.context.fillText("Hello World.", 200, 10, 200);
	};
	function loaded() {
		window.snippet = new SnippetCanvas();
		window.snippet.drawGrid();
		window.snippet.drawRect();
		window.snippet.drawCircle();
		window.snippet.drawPolygon();
		window.snippet.drawText();
	}
	if(document.addEventListener){
		document.addEventListener("DOMContentLoaded", loaded, false);
	} else if(/msie/.test(navigator.userAgent.toLowerCase())){
		try {
			document.documentElement.doScroll("left");
		} catch(error){
			setTimeout(arguments.callee, 0);
			return;
		}
		loaded();
	}
}).call(this);