Locations of the Screen
The HTML code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="sizeCanvas.js"> </script>
</head>
<body>
<h1>Locations of the Screen</h1>
<script>
// create a default canvas.
var canvas1 = new SizeCanvas();
// create a small canvas.
canvas1.SetClearColor("white");
canvas1.Redisplay();
</script>
<p>
<script>
var canvas2 = new SizeCanvas(100,100);
canvas2.Redisplay();
</script>
<p>
<script>
var canvas3 = new SizeCanvas(500,500);
canvas3.SetClearColor("blue");
canvas3.Redisplay();
</script>
</body>
</html>
sizeCanvas.js
function SizeCanvas(width, height) {
// make sure that widht and height are good.
if (width == undefined || width < 0) {
width = 300;
}
if (height == undefined || height < 0) {
height = 300;
}
// create the canvas
var canvas = document.createElement('canvas')
canvas.height = height;
canvas.width = width;
// add it to the document
document.body.appendChild(canvas);
// save some infor as local values
this.width = width;
this.height = height;
this.clearColor = "#000000";
this.ctx = canvas.getContext("2d");
return this;
}
SizeCanvas.prototype = {
SetClearColor: function(color) {
this.clearColor = color;
return;
},
Clear: function() {
this.ctx.fillStyle=this.clearColor;
this.ctx.fillRect(0,0,this.width,this.height);
return;
},
Redisplay: function() {
function LabelPoint(ctx, x, y, end) {
var line = "(" + x + "," + y + ")";
ctx.strokeStyle="purple";
if (end) {
ctx.textAlign="end";
ctx.strokeText(line, x-5, y);
} else {
ctx.textAlign="start";
ctx.strokeText(line, x+5, y);
}
};
var startx, starty, endx, endy;
// clear the canvas
this.Clear();
// compute the end points.
startx = this.width*.1;
endx = this.width * .9;
starty = this.height*.1;
endy = this.height * .9;
// draw the line
this.ctx.beginPath();
this.ctx.strokeStyle="#ff2233";
this.ctx.moveTo(startx, starty);
this.ctx.lineTo(endx, endy);
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.strokeStyle="lightgreen";
this.ctx.moveTo(startx, endy);
this.ctx.lineTo(endx, starty);
this.ctx.stroke();
LabelPoint(this.ctx, startx, starty, false);
LabelPoint(this.ctx, startx, endy, false);
LabelPoint(this.ctx, endx, starty, true);
LabelPoint(this.ctx, endx, endy, true);
return;
}
}