時間計測サンプル

ストップウォッチ

ストップウォッチ ソース

<canvas id="canvas1" width=300 height=100></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas1");
var context = canvas.getContext("2d");
context.font = "36px 'Times New Roman'";

var drawId;
var startTime;

function dispTime(h, m, s) {
	context.fillText(h + " hour " + m + " min " + s + " sec", 10, 50);
}

function zeroTime() {
	context.clearRect(0, 0, canvas.width, canvas.height);
	dispTime(0, 0, 0);
}

function start() {
	zeroTime();
	startTime = new Date();
	drawId = setInterval(draw, 1000);
	var t = document.getElementById("runButton");
	t.value = "Stop";
	t.onclick = stop;
}

function stop() {
	clearInterval(drawId);
	var t = document.getElementById("runButton");
	t.value = "Start";
	t.onclick = start;
}

function draw() {
	context.clearRect(0, 0, canvas.width, canvas.height);
	now = new Date();
	datet = parseInt((now.getTime() - startTime.getTime()) / 1000);
	hour = parseInt(datet / 3600);
	min = parseInt((datet / 60) % 60);
	sec = datet % 60;
	dispTime(hour, min, sec);
}
zeroTime();
</script>
<input type = "submit" value = "Start" id = "runButton" onClick = "start()"/>