<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Canvas Basics</title>
</head>
<body>
<div id="divcan">
<div id="doIt1">box arc</div>
<div id="doIt2">trig</div>
<div id="doIt3">clear</div>
<canvas id="can" width="400" height="400">NO!</canvas>
</div>
</body>
</html>
canvas{
background:#eee; }
#divcan{
margin:3px auto;
border:1px black solid;
padding:5px;
width:400px;
background:#999;
}
#doIt1, #doIt2, #doIt3{
float:left;
margin:2px;
border:1px black solid;
padding:3px;
width:32%;
text-align:center;
box-sizing: border-box;
background:#ffc;
}
var ctx;
function $(id) {
return document.getElementById(id);
}
window.onload = function() {
ctx = $("can").getContext("2d");
$("doIt1").addEventListener("click",boxArc);
$("doIt1").addEventListener("mouseover",boxArc);
$("doIt2").addEventListener("click",trigs);
$("doIt3").addEventListener("mouseover",clear);
};
function randomRGBA(){
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
var a = Math.random() + 0.2; // + .2 to see
// create string + random values inserted
var c = "rgba(" + r + "," + g + "," +
b + "," + a + ")";
return c;
}
function boxArc() {
var x = Math.random() * 300;
var y = Math.random() * 350;
ctx.strokeStyle="black";
ctx.lineWidth=3;
//
ctx.beginPath();
ctx.fillStyle=randomRGBA();
ctx.rect(x,y,50,50);
ctx.stroke();
ctx.fill();
//
ctx.beginPath();
ctx.fillStyle=randomRGBA();
ctx.rect(x+25,y+25,50,50);
ctx.stroke();
ctx.fill();
//
ctx.beginPath();
ctx.fillStyle=randomRGBA();
ctx.arc(x-5, y-25, 30, 0, Math.PI*2, false);
ctx.stroke();
ctx.fill();
//
ctx.beginPath();
ctx.fillStyle=randomRGBA();
ctx.arc(x+75, y+75, 30, 0, Math.PI*2, false);
ctx.stroke();
ctx.fill();
}
function trigs() {
var a; // angle
var offset = Math.floor(Math.random()*200)+50; // move it
// sin is y on unit circle - red
ctx.fillStyle="#f00";
// 3 waves, 3 circles each 2pi rads, by.2
for(a=0; a < 3*(Math.PI*2); a+=0.2){
ctx.fillRect(a*20,
offset + Math.sin(a)*20,
3, 3);
}
// cos is x on unit circle - green
ctx.fillStyle="#0f0";
for(a=0; a<3*(Math.PI*2); a+=0.2){
ctx.fillRect(offset + Math.cos(a)*20,
a*20,
3, 3);
}
}
function clear(){
ctx.clearRect(0, 0, $("can").width, $("can").height);
}
Also see: Tab Triggers