box-o-sand/html5/canvas/mdn-tutorial.html

103 lines
2.7 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>MDN Canvas Tutorial</title>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="tut0" width="150" height="150"></canvas>
<canvas id="tut1" width="150" height="150"></canvas>
<canvas id="tut2" width="150" height="150"></canvas>
<canvas id="tut3" width="150" height="150"></canvas>
<canvas id="tut4" width="150" height="200"></canvas>
<script type="text/javascript">
var drawings = {};
drawings.draw0 = function () {
var ctx = document.getElementById('tut0').getContext('2d');
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 55, 50);
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
ctx.fillRect(30, 30, 55, 50);
};
drawings.draw1 = function() {
var ctx = document.getElementById('tut1').getContext('2d');
ctx.fillRect(25, 25, 100, 100);
ctx.clearRect(45, 45, 60, 60);
ctx.strokeRect(50, 50, 50, 50);
};
drawings.draw2 = function() {
var ctx = document.getElementById('tut2').getContext('2d');
ctx.beginPath();
ctx.arc(75, 75, 50, 0, Math.PI*2, true);
ctx.moveTo(110, 75);
ctx.arc(75, 75, 35, 0, Math.PI, false);
ctx.moveTo(65, 65);
ctx.arc(60, 65, 5, 0, Math.PI*2, true);
ctx.moveTo(95, 65);
ctx.arc(90, 65, 5, 0, Math.PI*2, true);
ctx.stroke();
};
drawings.draw3 = function() {
var ctx = document.getElementById('tut3').getContext('2d');
ctx.beginPath();
ctx.moveTo(25, 25);
ctx.lineTo(105, 25);
ctx.lineTo(25, 105);
ctx.fill();
ctx.beginPath();
ctx.moveTo(125, 125);
ctx.lineTo(125, 45);
ctx.lineTo(45, 125);
ctx.closePath();
ctx.stroke();
};
drawings.draw4 = function() {
var ctx = document.getElementById('tut4').getContext('2d');
for(var i=0; i<4; i++) {
for(var j=0; j<3; j++) {
ctx.beginPath();
var x = 25+j*50,
y = 25+i*50,
radius = 20,
startAngle = 0,
endAngle = Math.PI+(Math.PI*j)/2,
anticlockwise = i%2==0 ? false : true;
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
if (i > 1) {
ctx.fill();
} else {
ctx.stroke();
}
}
}
};
window.addEventListener('load', function() {
for(funcname in drawings) {
console.log("Calling %s", funcname);
drawings[funcname]();
}
}, false);
</script>
</body>
</html>