JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<title> Canvas Experiment </title>
</head>
<body>
<div id="graph">
<canvas id="canvas" height="400" width="600">
<p>No Canvas Support</p>
</canvas>
</div>
</body>
</html>
CSS
#graph {
height: 200px;
width: 300px;
}
#canvas {
border: 1px solid #CCC;
}
JavaScript
var canvas = $("#canvas");
ctx = canvas[0].getContext("2d");
var CANVAS_HEIGHT = canvas[0].height,
CANVAS_WIDTH = canvas[0].width,
STROKE_STYLE_DEFAULT = "#000000",
FILL_STYLE_DEFAULT = "#000000",
LINE_WIDTH_DEFAULT = 1,
LINE_CAP_DEFAULT = "round",
LINE_JOIN_DEFAULT = "round",
GLOBAL_ALPHA_DEFAULT = 1;
function init() {
clearCanvas(ctx);
}
function clearCanvas() {
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
function setStyle(styles) {
if (styles.strokeStyle !== undefined) {
ctx.strokeStyle = styles.strokeStyle;
} else {
ctx.strokeStyle = STROKE_STYLE_DEFAULT;
}
if (styles.fillStyle !== undefined) {
ctx.fillStyle = styles.fillStyle;
} else {
ctx.strokeStyle = FILL_STYLE_DEFAULT;
}
if (styles.lineWidth !== undefined) {
ctx.lineWidth = styles.lineWidth;
} else {
ctx.lineWidth = LINE_WIDTH_DEFAULT;
}
if (styles.lineCap !== undefined) {
ctx.lineCap = styles.lineCap;
} else {
ctx.lineCap = LINE_CAP_DEFAULT;
}
if (styles.lineJoin !== undefined) {
ctx.lineJoin = styles.lineJoin;
} else {
ctx.lineJoin = LINE_JOIN_DEFAULT;
}
if (styles.globalAlpha !== undefined) {
ctx.globalAlpha = styles.globalAlpha;
} else {
ctx.globalAlpha = GLOBAL_ALPHA_DEFAULT;
}
}
function drawLine(coords, styles) {
ctx.beginPath();
ctx.moveTo(coords.x1, coords.y1);
ctx.lineTo(coords.x2, coords.y2);
// Doesn't work, why the fuck?
// setStyle( { "strokeStyle" : "#FF0000" } );
ctx.strokeStyle = "#F00";
ctx.stroke();
}
init(ctx);
// Zero positions of the ruler lines - in the middle of the canvas area
drawLine({
"x1": parseInt(CANVAS_WIDTH / 2),
"y1": 0,
"x2": parseInt(CANVAS_WIDTH / 2),
"y2": CANVAS_HEIGHT
});
drawLine({
"x1": 0,
"y1": parseInt(CANVAS_HEIGHT / 2),
"x2": CANVAS_WIDTH,
"y2":...