Graphics PRIMER functions
by brouser
HTML
<h1>Canvas Element Demo</h1>
<canvas id = "myCanvas" width = "400" height = "400">
Sorry, your browser doesn't support canvas elements!
</canvas>
CSS
canvas {
border: 3px dotted blue;
}
JavaScript
// these two variables are always needed
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// surface what the context actually is
// alert(ctx);
// reusable function to create Fill Color Rectangles
function makeFillColorRect(topLeftX, topLeftY, width, height, color) {
ctx.fillStyle = color;
ctx.fillRect(topLeftX, topLeftY, width, height);
}
// reusable function to create Stroke Color Rectangles
function makeStrokeColorRect(topLeftX, topLeftY, width, height, color) {
ctx.strokeStyle = color;
ctx.strokeRect(topLeftX, topLeftY, width, height);
}
function makeFillColorCircle(xCenter, yCenter, radius, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(xCenter, yCenter, radius, 0, Math.PI * 2, false);
ctx.fill();
}
function makeStrokeColorCircle(xCenter, yCenter, radius, color) {
ctx.strokeStyle = color;
ctx.beginPath();
ctx.arc(xCenter, yCenter, radius, 0, Math.PI * 2, false);
ctx.stroke();
}
function makeFillColorText(showWords, textX, textY, color, fontSize) {
sizeAndTypeface = String(fontSize + "px sans-serif");
ctx.font = sizeAndTypeface;
ctx.fillStyle = color;
ctx.fillText(showWords, textX, textY);
}
function makeStrokeColorText(showWords, textX, textY, color, fontSize) {
sizeAndTypeface = String(fontSize + "px sans-serif");
ctx.font = sizeAndTypeface;
ctx.strokeStyle = color;
ctx.strokeText(showWords, textX, textY);
}
// function call to create red fill color rectange @ (20, 20)
makeFillColorRect(20, 20, 150, 100, "red");
makeStrokeColorRect(190, 20, 150, 100, "blue");
makeFillColorCircle(95, 150, 50, "green");
makeStrokeColorCircle(265, 150, 50, "orange");
makeFillColorText("Get REKT!", 25, 275, "purple", 25);
makeStrokeColorText("Get ROASTED!", 25, 325, "magenta", 25);