Currently i'd like to read out the background color of a css through javascript to update a canvas with the desired color. So far i get it to work by creating a dummy object within html that holds that css from which i can read it:
The CSS content:
.logmessage-debug {
color: #fff;
background-color: #999999;
}
.logmessage-info {
color: #fff;
background-color: #5cb85c;
}
.logmessage-warn {
color: #fff;
background-color: #f0ad4e;
}
.logmessage-error {
color: #fff;
background-color: #d9534f;
}
.logmessage-fatal {
color: #fff;
background-color: #d955d9;
}
The HTML part:
<canvas id="myCanvas" width="200" height="200"></canvas>
<!-- The dummy objects allowing access to the css properties -->
<div id="debug" class="logmessage-debug"></div>
<div id="info" class="logmessage-info"></div>
<div id="warn" class="logmessage-warn"></div>
<div id="error" class="logmessage-error"></div>
<div id="fatal" class="logmessage-fatal"></div>
<script type="text/javascript">
updateCanvas();
</script>
The JavaScript part:
function updateCanvas() {
$.ajax({
url: "api/myWebService",
success: function (severityLevel) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = getSeverityColorFromStyle(severityLevel);
ctx.fillRect(0, 0, c.clientWidth, c.clientHeight);
},
complete: function() {
setTimeout(updateCanvas, 2000);
}
})
}
function getSeverityColorFromStyle(styleName) {
// Any other way to read the css background color
// directly instead of asking the dummy object?
return $("#" + styleName).css("background-color");
}
So far the above way works as expected and i can get out the desired colors i like. But I'm feeling uncomfortable by adding these dummy objects just to get access to the needed css values. Exists there any direct way to retrieve these values out of the css?