|
CS479/579 - Web Programming II
|
Displaying ./code/ES/paint.html
<!-- A HTML comment -->
<!DOCTYPE html>
<html onmousedown='start(event);' onmouseup='stop();' onmousemove='move(event);'>
<head>
<title> Paint </title>
<meta charset='utf-8'>
<!--
<link rel='stylesheet' src='styles.css' type='text/css' />
-->
<style>
.box { width: 50px; height: 50px; border: 1px solid black; cursor: pointer;}
#c { border: 1px solid black; cursor: crosshair;}
</style>
<script>
var _color = "black"; // The Pen color
var _drawing = false; // Boolean indicating that the mouse button is held down
var _ctx = null; // The 2D drawing context for our canvas
var _off = null; // Contains the canvas x,y offsets.
/**
* This function computes the x,y offset of the elements upper left corner w/
* respect to the browser window. We use this to determine exactly where in
* the browser window the canvas is so we can adjust the mouse coordinates
* (which are always relative to the upper/left corner of the browser window)
* w/ respect to this offset.
*/
function offsets(e) {
var xo = 0, yo = 0;
// Walks up the offsetParent tree, adding the offsets
do {
xo += e.offsetLeft;
yo += e.offsetTop;
} while (e = e.offsetParent);
return {xo : xo, yo : yo};
}
// On document load, initialize the global variables above and set the
// strokeStyle.
function init() {
var c = document.getElementById("c");
_off = offsets(c);
_ctx = c.getContext("2d");
_ctx.strokeStyle = _color;
}
// Sets the pen color to this elements background color:
function setcolor(e) {
_color = e.style.backgroundColor;
_ctx.strokeStyle = _color;
}
// Start drawing (onmousedown)
function start(ev) {
_drawing = true;
_ctx.beginPath();
_ctx.moveTo(ev.clientX-_off.xo, ev.clientY-_off.yo);
}
// Stop drawing (onmouseup):
function stop() {
_drawing = false;
_ctx.closePath();
}
// When moving, add a new line segment ending at the current mouse position
// to the current path and call the stroke() method to draw the path:
function move(ev) {
if (_drawing == false) return;
_ctx.lineTo(ev.clientX-_off.xo, ev.clientY-_off.yo);
_ctx.stroke();
}
</script>
</head>
<body onload='init();'>
<table>
<tr>
<td>
<div class='box' onclick='setcolor(this);' style='background: white;'></div>
<div class='box' onclick='setcolor(this);' style='background: black;'></div>
<div class='box' onclick='setcolor(this);' style='background: red;'></div>
<div class='box' onclick='setcolor(this);' style='background: green;'></div>
<div class='box' onclick='setcolor(this);' style='background: blue;'></div>
<div class='box' onclick='setcolor(this);' style='background: yellow;'></div>
<div class='box' onclick='setcolor(this);' style='background: orange;'></div>
<div class='box' onclick='setcolor(this);' style='background: purple;'></div>
<div class='box' onclick='setcolor(this);' style='background: cyan;'></div>
<td><canvas id='c' width=640 height=480></canvas>
</body>
</html>
|