Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style canvas elements with CSS

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/

like image 618
Miroslav Nedyalkov Avatar asked Apr 16 '15 12:04

Miroslav Nedyalkov


1 Answers

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.

like image 134
Elad Stern Avatar answered Sep 27 '22 21:09

Elad Stern