Styling Drawn Elements on a Canvas Using CSS

Can CSS Animations be applied to a circle drawn on a canvas using JavaScript? Specifically, I am using an AngularJS directive for this purpose: https://github.com/angular-directives/angular-round-progress-directive/blob/master/angular-round-progress-directive.js

The goal is to have the circle glow every second, and I already have the CSS code for the animation. Is this achievable?

Alternatively, would it be better to make the canvas itself circular and apply the glowing effect directly to the canvas?

Answer №1

Applying CSS to elements in the canvas is not possible since they are not part of the DOM. They are essentially like bitmap images.

One alternative is to use an SVG circle instead, which allows for styling with CSS and animations:

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

Answer №2

If you want to add a glow effect to shapes drawn on canvas, you can't apply CSS directly, but you can achieve the effect by utilizing shadows.

Check out this demo for an example

var canvas = document.getElementById('canvas'), 
    ctx = canvas.getContext('2d'),              
    w = canvas.width,                           
    h = canvas.height,
    cx = w * 0.5,
    cy = h * 0.5,
    glow = 0,                                   
    dlt = 1,                                    
    max = 40;                                   

ctx.shadowColor = 'rgba(100, 100, 255, 1)';     
ctx.fillStyle = '#fff';                         
    
function animate() {
    ctx.clearRect(0, 0, w, h);                  
    ctx.shadowBlur = glow;                      

    ctx.beginPath();                            
    ctx.arc(cx, cy, cx * 0.25, 0, 6.28);
    ctx.fill();                                 
    
    glow += dlt;                                
    if (glow <= 0 || glow >= max) dlt = -dlt;

    requestAnimationFrame(animate);                
}
animate();

Update

To create an outline with an outer glow effect, you can "punch out" the center of the circle using a composite operation. The following modification demonstrates how to achieve this:

ctx.fillStyle = '#fff';
// remove shadow from global

function animate() {
    ctx.clearRect(0, 0, w, h);

    // draw main circle and glow
    ctx.save();                                     
    ctx.shadowColor = 'rgba(100, 100, 255, 1)';
    ctx.shadowBlur = glow;

    ctx.beginPath();
    ctx.arc(cx, cy, cx * 0.25, 0, 6.28);
    ctx.fill();    
    ctx.restore();                                  

    // draw inner circle
    ctx.globalCompositeOperation = 'destination-out'; 
    ctx.beginPath();
    ctx.arc(cx, cy, cx * 0.23, 0, 6.28);          
    ctx.fill();    
    ctx.globalCompositeOperation = 'source-over'; 

    glow += dlt;
    if (glow <= 0 || glow >= max) dlt = -dlt;

    requestAnimationFrame(animate);
}

The composite operation removes pixels from the next draw operation. By drawing a smaller filled circle on top, you can create an outline of the first circle with its glow effect intact.

View the modified demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Access not granted while utilizing Yeoman for scaffolding an application

Having some trouble setting up a new project with Yeoman and Angular. I've tried running "yo angular" and "yo app", but keep encountering the same error message. Unfortunately, I'm not very familiar with Terminal. Error: EACCES, permission denie ...

Tips for restricting navbar-fixed to the width of the container

Welcome to my first project utilizing Twitter Bootstrap. While using Twitter Bootstrap, I've noticed that whether I use container-fluid or just container for my fixed top navbar, it expands to full width of the browser once it reaches around 980px. T ...

Trouble with applying CSS class to checkboxlist

I am trying to display a border around each checkbox item in a checkboxlist. I believe that it can be achieved by setting the td cssclass as the checkboxlist saves items in td. However, the code I tried below is not working. Here is the ASPX code: < ...

2 unique personalized classes with individualized modifications

Is it feasible to create 2 distinct custom (a tag) classes, each with unique class names? For Instance: When I try to use these in my HTML code, I struggle to create 2 different styles for (a tag) with different names! <a class="type1" href="#">te ...

Achieve full width with flexbox column wrap while minimizing the height

How can I arrange elements in columns within a container with a fixed width and variable height, when the number of elements is unknown? My challenge is that I do not know the maximum width of the child elements, preventing me from setting specific column ...

Troubleshooting: Twitter Bootstrap dropdown feature experiencing issues within navigation bar

I am facing an issue with getting the bootstrap dropdown to function properly. I have tested it on my mobile device and noticed that the menu does not drop down as expected. Here is a DEMO Below is the code snippet: <nav class="navbar navbar-inverse ...

How come I am able to reference a component in styled-components while others cannot?

When using styled-components, you can reference another React component using the syntax ${Label}. However, I have noticed that it only works with certain components and not others. Despite reading the documentation at , I encountered an issue when trying ...

Moving the layout container towards the left: a quick guide

I am currently attempting to display the legend contents in a horizontal alignment within the layout container. The issue is that while the layout containing the legend aligns horizontally as desired, it extends beyond the screen border. I do not want the ...

The Google Chart is failing to show up on the screen

I'm having trouble implementing a feature that involves selecting a region from a dropdown list and requesting rainfall data to display in a Google Chart. Unfortunately, I've encountered some issues with it. Could you please help me identify ...

"Finding the Perfect Alignment: How to Center Legends in Firefox

The issue at hand An issue has been identified where the code functions as intended in Chrome, Opera, and IE but fails to work in Firefox: fieldset>legend { display: table; float: none; margin: 0 auto; } <fieldset> <legend>Legend ...

Tips for creating a navigation system that combines both horizontal and vertical bars

Is there a way for me to have both horizontal and vertical navigation bars on my website? I am new to design and struggling to understand why my CSS isn't working properly when applied to multiple links. <body> <div class="horizontallinks" ...

Creating a dynamic shift in background color

Is it possible to use jQuery to slowly change the color of diagonal lines in a background styled with CSS, while also adding a fading effect? I have created a fiddle with the necessary CSS to display a static background. You can view it here: http://jsfid ...

There was an issue stating that valLists is not defined when paginating table rows with AngularJS and AJAX

I found a helpful code snippet on this website for implementing pagination in AngularJS. I'm trying to adapt it to work with data from a MySQL DB table called 'user', but I keep running into an issue where the valLists variable is undefined, ...

Error Handling in Angular2 MVC 4 Project Route Issues

Here is the structure of my Mvc 4 Project with angular 2 implemented: Solution 'Angular2Starter' |-- angular2Starter | `-- Controllers | `-- HomeController.cs |-- src | |-- app | | |-- home | | | |-- home.component.ts | ...

Having trouble adding your own styling to bootstrap-4 using a custom CSS file?

Here is the code I used to connect my two stylesheets, with the custom css file being linked second as per what I believe is the correct way to do it. <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href=" ...

Determine whether a WebElement contains a particular content within the :after pseudo class

After locating my element in Selenium, I've come across an interesting challenge. IWebElement icon = box.FindElement(By.ClassName("box-icon")); Sometimes, this element (icon) has a content set as follows: &:after { content: $icon-specia ...

Issue with IE11: Flexbox with absolute positioning not sizing correctly, fills entire width instead of individual content

Here's a simple case to reproduce the issue: <div style="display: inline-block; position: relative; border: 1px solid black;"> short <div style="display: flex; position: absolute; border: 1px solid black; top: 100%; lef ...

The icons in webviews on mobile apps (iOS and Android) fail to render correctly

My font icons are behaving inconsistently on webkit-based mobile browsers when used on mobile devices. When hovering over the span on a desktop browser, the icon properly fills its container: However, when hovering over the span on a mobile device, the i ...

Tips for achieving printing with the "Fit sheet on one page" option in JavaScript

Is there a way to print a large table of data with 200 or 300 rows all on one page, similar to the Online MS Excel print option 'Fit Sheet on One Page'? I attempted the code below: var tble = document.createElement("table"); tble.id = "tble"; d ...

Order ArrayList elements based on specified conditions using SQL query or Java

Within my database, I have a table for employees that includes columns such as emp_id, superior_id, and name. I am attempting to create a tree structure using a JavaScript library. Each employee has a superior_id except for the manager. In order to achie ...