Applying CSS on Drawn Canvas Elements

Applying CSS on drawn Canvas Elements

You can't apply CSS to elements drawn in the canvas, because they don't exist on the DOM. It's just as if they were a bitmap image.

You could use an SVG circle though, which will allow you to style the circle with CSS and use animations:

<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

Using CSS to style elements drawn to a canvas

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.

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];
}

Can I give a class to a path drawn on a canvas with javascript?

No, CSS cannot animate or interact with canvas drawing.

But You can create a Star class which will provide OOP way of updating, rendering and animating the stars.

and then push all of the stars in an array and update/render them on animate loop.

https://codepen.io/anuraghazra/pen/WLLQJv

Add style to elements inside HTML5 canvas

Setting CSS styles only affects elements, here the image element.

When you draw the image to canvas you don't draw the element but the image's bitmap. Canvas is just that, a bitmap and is not related to CSS or DOM per-SE (it's a DOM element but everything that happens inside it is "low-level" bitmap manipulation).

To simulate border for an image drawn to canvas you can draw it on top:

context.drawImage(image, 5, 5);
context.lineWidth = 3;
context.strokeStyle = '#00f';
context.strokeRect(5, 5, image.width, image.height);

(offset the x and y position by 0.5 pixel to make the border sharp).

Modified fiddle

PS: Also remember to handle image loading properly using the onload handler as loading images is asynchronous (updated fiddle with this as well).

add circle with specific style to canvas

Unfortunately, there is no way for you to simply put a <div> inside the <canvas> element and make it magically draw on the canvas. That said, you can draw/animate this image the same way you are right now inside the canvas with JavaScript instead.

I'm not going to just write all of the code for you, but I will explain some concepts for you to research.

To animate:

  • requestAnimationFrame(functionName)

    • Update the canvas element every frame

    • Draw everything inside that function to render every frame

To update image

  • Use the rotate() and translate() methods (similar to your css)

To draw circle

ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.clip();
ctx.drawImage(image, 0, 0, width, height);

Reference for every Canvas method you will need to use

Reference for requestAnimationFrame

Alternatively, you could simply style the <div> to be on top of the canvas, but you cannot draw it inside the canvas without using JS.

How to draw an image inside a html canvas with JavaScript for special filters

You can achieve the same effect from the 2D context API by reproducing what your CSS is doing, step by step.

The first step is to draw the image (first background image) with an offset of -1 -1.
This can be easily achieved by using drawImage().

const img = new Image();img.onload = function() {  const imageWidth = 800  const imageHeight = 600  const canvas = document.getElementById("canvas");  canvas.width = imageWidth;  canvas.height = imageHeight;  const context = canvas.getContext("2d");
// first pass without any filter nor blending // simple offset context.drawImage(img, -1, -1, imageWidth, imageHeight)};img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Point_Reyes_Lighthouse_%28April_2012%29.jpg/593px-Point_Reyes_Lighthouse_%28April_2012%29.jpg";
<canvas id="canvas" style="background: red"></canvas>


Related Topics



Leave a reply



Submit