HTML and CSS Reference
In-Depth Information
<body style="text-align: center; margin: 1in;">
<canvas id="square" width="400" height="400"
style="border: thin solid">
Sadly, your browser does not support the <em>canvas</em> element.
</canvas>
<div>
<button onclick="draw('red')">
red
</button>
<button onclick="draw('orange')">
orange
</button>
<button onclick="draw('yellow')">
yellow
</button>
<button onclick="draw('green')">
green
</button>
<button onclick="draw('aqua')">
aqua
</button>
<button onclick="draw('blue')">
blue
</button>
<button onclick="draw('violet')">
violet
</button>
</div>
<script type="text/javascript">
/* Get the canvas element and establish a drawing context */
var canvas = document.getElementById("square");
var square = canvas.getContext("2d");
var offset = 0; var sqsize = 400;
/* function to draw a filled square */
function draw(color) {
square.fillStyle = color;
square.fillRect(offset, offset, sqsize, sqsize);
if (sqsize > 40) { offset += 20; sqsize -= 40; }
}
</script>
</body>
</html>
he
canvas
element deined in Example 2.27 is blank to begin with. It has
a light border around it just so we can see where it is in this example. here
is no requirement to visually display a
canvas
element before any drawing
takes place. Each of the buttons below the canvas calls the
draw
function when
clicked, with the associated color name as an argument to the function. he