Using CSS to style elements drawn to a canvas

- 1 answer

Ad

At the moment, we use hardcoded styles when writing text on a canvas:

    ctx.setTransform(1,0,0,1,0,0);
    ctx.fillStyle = "#2F353C";
    ctx.font = "15px 'Roboto', sans-serif";
    ctx.fillText(varName || '', 5, 12);

I would dearly love to store that actual style information in CSS files, and access it from there somehow. (I'm not expecting miracles, like CSS to magically apply to elements rendered within the canvas...)

The only way I can think of would be to create some text elements behind our canvas, assign them classes, and then somehow access their computed properties, transferring them to the canvas elements.

Is there a better way?

Ad

Answer

Ad

Warning

This answer should be removed but as it has been accepted I am unable to. Below is the answer as is, but there are a host of problems and browser compatibility issues, making this answer impractical.

SVG markup for canvas

If you use SVG images to render to the canvas you can add CSS style rules to the elements within the SVG and as long as you continue to render the SVG it will reflect all the rules, including animations and other time based FX.

SVG markup with CSS

<!-- within the SVG element -->
<svg>
<style>
/* CSS */
#buttonWhite {  /* ID name */
   fill:white;
   font-size:12px;
}
#buttonBlue {
   fill:blue;
   font-size:16px;
}
</style>
<text id="buttonWhite" x="100" y="100">I am white</text>
<text id="buttonBlue" x="100" y="200">I am blue</text>
</svg>

Script

// within the script
var svg = new Image();
svg.src = "SVG_URL.svg";

// once svg has loaded then display it on the canvas
ctx.drawImage(svg,0,0);

If you make changes to the CSS or SVG you need to rerender it to see the changes.

UPDATE

For more information on linking in CSS see MDN SVG & CSS

I had made a mistake in the CSS forgetting that SVG has its own styles. I have corrected it by replacing color with fill.

Ad
source: stackoverflow.com
Ad