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

ShadCn UI ResizablePanelGroup effortlessly grows within the available area without the need to set a specific height

I'm facing a CSS challenge with the ResizablePanelGroup component. My layout includes a header and a ResizablePanelGroup with 4 panels. The page should take up 100% of the viewport height, and I want other components to be placed within it. Once the H ...

Ensure that the navbar remains within the container as you scroll down the page

With the implementation of bootstrap 4, I have successfully integrated a fixed navbar inside a container. Initially, at the top of the page, it occupies the full width, but as soon as I start scrolling, it smoothly transitions into the confines of the cont ...

How to prevent click events and still enable scrolling within a DIV using CSS/JS

Basically, I am looking to enable scrolling within a DIV while also disabling click events. Any suggestions on how this can be achieved? Appreciate any help! ...

Ways to activate side-to-side scrolling?

Here on this specific page, I am looking to showcase the SPECIAL and RECOMMENDED sections together in a single line with horizontal scrolling. This is my current CSS: .box-product { width: 100%; overflow: auto; } I have attempted implementing it like th ...

Tips for creating unit tests for a controller that relies on a factory service that in turn relies on the $http service

I've been grappling with the concept of unit testing in AngularJS using Jasmine and Karma for a simple app. Despite my attempts to search online, I haven't been able to make much progress, especially when it comes to mocking and injecting a facto ...

Managing image alignment in flexbox containers with nested rows and columns

In the following design demonstration, there are three blocks to explore. Block 1: Consists of three columns. The middle column contains two rows, both set to flex:1. Block 2: Also has three columns. The middle column includes two rows, but with a unique ...

Resize the images and align them side by side

I have a container with a maximum width of 1400px. Inside this container, there are two images of different sizes. I want to align them in a row using flexbox so that they fit within the 1400px width and still maintain a visually appealing appearance as sh ...

Tips for converting an object into parameters for ng-include

What is the best way to create a serialized array of objects that can be used as parameters for ng-include in order to dynamically load data from the server? Using Angular controller and params with requests: app.controller("MyCtrl", function($scope) { ...

What is the best way to manage the browser tab close event specifically in Angular, without it affecting a refresh?

I am trying to delete user cookies when the browser tab is closed. Is this achievable? Can I capture the browser tab close event without affecting refreshing? If I attempt to use beforeunload or unload events, the function gets triggered when the user ref ...

What steps do I need to follow in order to replicate the layout shown in this

I am struggling with creating a layout in CSS that resembles the one shown in this photo: enter image description here Here is the HTML structure I have, but I can't figure out how to style it properly. <ul class="list"> ...

Is it better to Angularize Symfony or Symfonyize Angular for Ajax?

When dealing with Ajax, it seems that Symfony (v. 2.7) and AngularJS (v. 1.4) may not be the best match ;-) I have identified two possible solutions to make them work together - my inquiry is: Which one is more effective? Adjust AngularJS to be compatib ...

Tips for applying a CSS class with a smooth fade-out effect

In my Angular project, I am working on creating a custom notification component. Here is the template code I have so far: <aside *ngFor="let message of messages "> <div class="notification" style="position:fixed"> {{message.conten ...

What are the main differences between Fluid Layout and Grid?

It seems like there's some vital information I haven't come across yet. Are fluid layouts and grid layouts interchangeable? I keep hearing about this baseline concept, but I can't quite grasp its purpose. Does it serve as a guide for alignin ...

Leveraging the power of modernizr in an angular module to handle multiple

My current setup involves the use of 'Modernizr' to detect mobile devices. I have also created a file called 'touchevent.js' specifically for these devices. Within touchevent.js: var touchApp = angular.module('ngTouchEvent', ...

Submitting a File Using AngularJS and PHP

Attempting to upload a file utilizing Angular JS and PHP through a formdata object. Wanting to utilize key1 (data) value as JSON to transmit filename and user info to the php script Opting for key2 (uploadFile), value being the file currently being uploa ...

Utilizing an Image as a Link in the Background

I am working on a way to convert the CSS background image I have into a clickable link that can be referenced. Here is my CSS code: #wrapper { height: 100%; padding: 66px; } #ad_11 { background-image: url(images/index1.png); display: block; text-indent: ...

Enhancing jQuery Mobile listview with voting buttons on each item row

I am looking to incorporate 2 vote buttons within a jQuery mobile listview, positioned on the left-hand side and centered within each list item. While I have managed to achieve this using javascript, my goal is to accomplish it without any additional scrip ...

Getting rid of the excess white space below the footer caused by concealed elements

In my design, I have three columns. The rightmost column is filled with 'Divs' containing collapsed information that can be scrolled through using the mouse wheel. The overflow in the center is hidden. The width of all three columns is set to 760 ...

Experience a seamless front/back DIV transition with a mouseover effect similar to the ones on USAT

Recently, I was tasked with creating a mouseover transition effect for a div similar to the one used on USAToday's website. The structure of the boxes on the site includes: <div class="asset"> <div class="front">'image and some t ...

CSS3 Feature: Chevron-shaped banner with jagged edges

I'm currently working on building a unique chevron-style banner using CSS3, but I've run into some aliasing problems specifically in Chrome. Despite trying to utilize the -webkit-backface-visibility: hidden attribute, I still can't seem to r ...