How to style canvas elements with CSS

I’m a bit late for the party but I just had the same scenario and I solved it like this:

// "Cache"
var classColors = {};

function getColor(className) {
    // Check for the color
    if (!classColors[className]) {

        // Create an element with the class name and add it to the dom
        $c = $('<div class="' + className + '"></div>').css('display', 'none');
        $(document.body).append($c);

        // Get color from dom and put it in the color cache
        classColors[className] = $c.css('color');

        // Remove the element from the dom again
        $c.remove();
    }

    // Return color
    return classColors[className];
}

I only needed the color but you can extend the cache object to hold more than color if you want. The you’d return a full object from the function. The below code is not tested at all:

var classProperties = {};

function getPropeties(className) {
    // Check for the properties object
    if (!classProperties[className]) {

        // Create an element with the class name and add it to the dom
        $c = $('<div class="' + className + '"></div>').css('display', 'none');
        $(document.body).append($c);

        // Get needed stuff from the dom and put it in the cache
        // P.S. Didn't test if canvas names are the same as css names.
        // If not you'll have to translate it
        classProperties[className] = {
            fillStyle: $c.css('color'),
            lineWidth: $c.css('border-width'),
            strokeStyle: $c.css('border-style')
        }

        // Remove the element from the dom again
        $c.remove();
    }

    // Return properties
    return classProperties[className];
}

Leave a Comment