Using JavaScript to animate a background composed of SVG shapes

My code is successfully adding an svg background with js and rotating it using set interval. It works perfectly on Chrome, but not on any other browser. Any suggestions on how to make it work universally?

let i = 0;
setInterval(() => {
    document.body.style.backgroundImage = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25'%3E...`

    if(i === 360){
        i = 0;
    } else {
        i++;
    }

}, 30);

Answer №1

Rebuilding the entire image from the serialized URL data is too time-consuming. A more efficient approach is to manually create the SVG code and animate the gradientTransform attribute. The code snippet below demonstrates rendering the <svg> element directly within the <body> tag of an HTML page.

There are two ways to declaratively implement the animation, both with their compatibility issues:

  • A SMIL animation using the <animateTransform> element will not function on Edge/IE browsers.
  • A CSS animation necessitates the utilization of the gradientTransform attribute defined as a presentation attribute, a feature introduced in SVG 2 that is not universally supported by all browsers (it is currently not functional on Firefox).

Thus, the scripted version is the optimal approach. It is advised to utilize the window.requestAnimationFrame() method to ensure smooth execution of the animation based on the browser's capability.

let start = null;
const gradient = document.querySelector('#a');
function step(timestamp) {
    if (!start) start = timestamp;
    const degree = (timestamp - start) / 30 % 360;
    gradient.setAttribute('gradientTransform', `rotate(${degree},814,458)`);
    window.requestAnimationFrame(step);
}

window.requestAnimationFrame(step);
body { height: 100vh; margin: 0; }
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
  <defs>
    <linearGradient id="a" gradientUnits="userSpaceOnUse" x1="0" x2="0" y1="0" y2="100%" gradientTransform="rotate(0,814,458)">
      <stop offset="0" stop-color="#0f63ff"/>
      <stop offset="1" stop-color="#d90fff"/>
    </linearGradient>
    <pattern patternUnits="userSpaceOnUse" id="b" width="504" height="420" x="0" y="0" viewBox="0 0 1080 900">
      <g fill-opacity="0.15">
        <polygon fill="#444" points="90 150 0 300 180 300"/>
        <polygon points="90 150 180 0 0 0"/>
        <polygon fill="#AAA" points="270 150 360 0 180 0"/>
        <polygon fill="#DDD" points="450 150 360 300 540 300"/>
        <polygon fill="#999" points="450 150 540 0 360 0"/>
        <polygon points="630 150 540 300 720 300"/>
        <polygon fill="#DDD" points="630 150 720 0 540 0"/>
        <polygon fill="#444" points="810 150 720 300 900 300"/>
        <polygon fill="#FFF" points="810 150 900 0 720 0"/>
        <polygon fill="#DDD" points="990 150 900 300 1080 300"/>
        ...
        <polygon fill="#DDD" points="1080 900 1170 750 990 750"/>
      </g>
    </pattern>
  </defs>
  <rect x="0" y="0" fill="url(#a)" width="100%" height="100%"/>
  <rect x="0" y="0" fill="url(#b)" width="100%" height="100%"/>
</svg>

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

Guide on transferring href parameter from the parent Vue component to the child component

Hey there! I've been working on creating a Vue page, breaking it down into components, and populating it with content from json. It all seems pretty straightforward, but I've hit a snag. Why is the href parameter not showing up in the right place ...

How to Implement Transition Effect for Height Changes on v-if in Vuejs

I have a code snippet that effectively animates a v-if element by reducing its height to 0px. The animation is working well, but the issue arises when I need to specify the initial height of the element in CSS. While this is fine for a single element, I ...

Enhance your Django website with the powerful jQuery Datatables plugin

I am relatively new to using django and I have integrated jquery datatable plugins into my django application. Currently, these datatables are functioning well with small datasets retrieved from my view. However, I am facing challenges when trying to displ ...

Height transition animation in Angular 2 - maintaining state consistency

I am currently working with an animation code that is linked to my component. animations:[ trigger('slide', [ state('show', style({ height: '*' })), state('hide ...

AngularJS: Blocking access to specific state for users

I am currently in the process of developing an application using sails.js for the backend and Angular for the frontend. My goal is to restrict access to the admin control page for unauthorized users. I have come across several solutions, but none of them s ...

React: Dynamically update text input based on selected option

After selecting an option, I want to display a new text input. However, the old value entered remains on the screen even when I change the selection. How can I improve this functionality? Any suggestions would be appreciated. class loadComponent extends ...

What is the best way to access a reference to the xgrid component in @material-ui?

Is there a way to obtain a global reference to the xgrid component in order to interact with it from other parts of the page? The current code snippet only returns a reference tied to the html div tag it is used in, and does not allow access to the compo ...

Remain on the React page following an HTTP POST request to Flask

Is there a way to stay on the React frontend (localhost 3000) after completing a POST request to a Flask backend from a React form, without redirecting in the Flask backend? Relevant code: export const DateForm = () => { return ( <div&g ...

Thumbnail with magnifying effect on image

I have a thumbnail that contains both an image and some text. When I hover over the image, it zooms in. Check out this demo here: https://jsfiddle.net/ShiroiOkami/r1awd3b4/ I am looking to achieve an effect where the image zooms in without changing i ...

What steps do I need to take to create a customizable Angular Material NPM module?

Can a custom npm module be created using Angular Material that allows the components to be styled by the consuming app's unique theme? For instance, imagine an npm module with a component containing the following template: <button mat-raised-butt ...

Watching a video play within a slider and transitioning seamlessly to an image once the video ends

I am currently facing an issue with a video playing inside a HeroCarousel slider. Before the slider, there is an image and after the slider, there is another image. This is my code: <div data-time="8000" data-prev-src="/media/splash/slider-left.png" ...

The button is effectively disabled for a few seconds as needed, but unfortunately, the form cannot be submitted again using that button

The button is disabled for a specific duration as required, but the form does not get submitted through that button again. Below is the script code written in the head tag $(document).ready(function () { $('.myform').on('submit', ...

Avoid triggering a keydown event if certain div elements have been clicked

When the user presses the space bar, my script is set up to perform certain actions, such as stopping an audio player: $('html').keydown(function(e){ if(e.keyCode == 32){ // Stop the audio player } } However, an issue arises when a ...

Tips on avoiding a div from causing its parent's mousemove event to activate if it is concealed

I have a collection of media content with a set of controls positioned above it. I am attempting to implement functionality where the controls will disappear when the user's mouse is inactive and reappear upon mouse movement. However, I am facing an ...

Ensuring the legitimacy of Rails form submissions

I am encountering an issue with validating a form before submitting it, as the form is being submitted without triggering the jQuery part. <%= form_for(:session,class:"form-signin form-horizontal",:id=> "form",:role=> "form") do |f| %> & ...

The catch block seems to be failing to capture the errors thrown by the fetch API

I am facing an issue with my code where the fetch method, enclosed within a catch block, fails to capture errors. Despite attempting various error handling approaches on my node backend, the problem persists. https://i.stack.imgur.com/0reJj.png const e ...

Is there a way to modify the location of the datepicker/calendar icon within my bootstrap form?

When using react-bootstrap with the <Form.Control type="date"> element, I noticed that the calendar icon or date picker is automatically positioned to the right side/end of the form field. However, I am interested in moving the calendar ico ...

Incorporating lazy loading for diverse content to enhance pagination

I'm currently using jpaginate for pagination on a large dataset, but I've noticed that all the content loads at once. Is there a jQuery plugin available that will only load the content for the current page? ...

React variable should remain consistent and not change unnecessarily

I've been struggling with an issue for about 3 hours now, and I just can't seem to figure it out. Let me walk you through the problem with the code snippet below: import {useEffect} from 'react' function shuffle(tab) { console.table ...

Using a straightforward approach with v-model in vue.js on an href element instead of a select

Is there a way to utilize an href-link instead of using <select> to switch languages with vue.i18n? <a @click="$i18n.locale = 'en'">EN</a> <a @click="$i18n.locale = 'da'">DA</a> ...