I have a lot of figures and elements drawn in the a HTML canvas. All of them have different colors, strokes, etc. I really don't like that all these values are wandering in my JS code as some styles are in the CSS and some are in the code.
Does somebody know a good way to define the styles in CSS and read the styles when actually rendering the objects?
Here is some example of what I need to do:
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green'; // I'd like to set with CSS
context.fill();
context.lineWidth = 5; // I'd like to set with CSS
context.strokeStyle = '#003300'; // I'd like to set with CSS
context.stroke();
http://jsfiddle.net/nedyalkov/ysgLqqh3/1/
CSS has a certain scope to it, that is, it only acts on HTML elements. Javascript, on the other hand, has its own variables and can also interact with HTML elements. What you're trying to do is use CSS as variables for javascript, which can't be done.
The code sample above represents a piece of javascript which takes an HTML element (in this case a canvas
) and performs a set of actions (methods) on it. What you're doing is literally drawing one line at a time to create your image, and this image is outside of the CSS scope as it is only defined by the elements internal properties, while CSS can only define its external (specifically, visual) properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With