Determining control points within the getBBox() method for SVG paths on Safari and Chrome

I am encountering an issue related to a bug documented here: https://code.google.com/p/svg-edit/wiki/BrowserBugs#getBBox_on_paths_with_curves_includes_control_points

When dealing with arcs (defined by center, radius, startAngle, endAngle), I can calculate points along the path and their bounding box. However, in Safari and Chrome, there is a bug that includes control points of the arc in the bounding box. This causes gradient fills to be applied differently depending on whether the browser is affected by the bug or not.

My inquiry is: How can I mathematically calculate the extra control points of an arc in a path to correct for the safari/chrome bug without relying on the getBBox() API? The parameters given are (center, radius, startAngle, endAngle).

This adjustment does not need to accommodate bezier curves or ellipses, just a straightforward circular arc. Any insights would be greatly appreciated!

Answer №1

I recently developed a workaround for the getBBox issue in webkit browsers. If you're facing similar challenges, check out this demo to see it in action.

// Fixing the getBBox bug for webkit (safari, chrome) path elements
if(navigator.userAgent.indexOf('AppleWebKit')>0){
    SVGPathElement.prototype.getBBox = function (precision){
        var path = this;
        var total = path.getTotalLength();
        if(total <= 0){
            return {x:0,y:0,width:0,height:0};
        }
        var segLen = precision || 1;
        var len = 0, pt, xarr = [], yarr = [];
        while(len < total){
            pt = path.getPointAtLength(len);
            xarr.push(pt.x);
            yarr.push(pt.y);
            len += segLen;
        }
        pt = path.getPointAtLength(total);
        xarr.push(pt.x);
        yarr.push(pt.y);
        var b = {};
        b.x = Math.min.apply(0,xarr);
        b.y = Math.min.apply(0,yarr);
        b.width = Math.max.apply(0,xarr) - b.x;
        b.height = Math.max.apply(0,yarr) - b.y;
        return b;
    };
}

Answer №2

If you're looking for a way to create a shim for the getBBox() function, check out how Snap.svg handles it in this code snippet: https://github.com/adobe-webplatform/Snap.svg/blob/master/src/path.js#L414

Specifically for a <path> DOM element, you can retrieve an accurate BBox by using the following method:

Snap.path.getBBox(pathElement.getAttribute('d'))

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

Looking for the properties of the ServerResponse object in node.js - where can I locate them?

Currently, I've been diving into the book Node.js In Action. Chapter 9 introduces a message module with a function that has left me puzzled about the 'this' object when calling res.message. To gain clarity, I decided to print out the name of ...

Horizontal Scrollbar on the Top and Bottom

I've spent the last few days searching for a viable solution to this particular dilemma. Basically, I have a div that requires a secondary scroll bar at the top in order to facilitate horizontal scrolling without having to navigate all the way to the ...

Unable to render backend-sourced images in ReactJS

I'm currently working on a project that involves displaying images fetched from the backend. I've been successful in displaying all the data except for the images. Below is the response I received when I logged the response: [ { "_id&qu ...

Converting HTML input to a file using JavaScript

Here is the React.js component code I'm working with: import React, {ChangeEvent, useState} from "react"; import { Button } from "@mui/material"; function UploadCVButton() { const [selectedFile, setSelectedFile] = useState(null ...

The SelectedIndexChanged event fails to trigger following an onchange event

I am currently working on validating a dropdown list on the client side based on its selected index/value. My goal is to create a function that triggers an alert when the selected index is 0, or alternatively execute the SelectedIndexChandged method in the ...

The async module has already been invoked with a callback function

Below is an array that I am working with: var files = [ { name: 'myfile.txt' }, { name: 'myfile2.txt' } ]; My goal is to access these objects asynchronously and send them for extraction, as shown below: Extraction function: ...

Exploring the various viewport sizes in Bootstrap breakpoints

I'm currently working on a responsive cropping tool for multiple devices using cropperjs. Right now, I am estimating the viewport sizes for each bootstrap breakpoint but I need to determine the actual height in order to establish a ratio. You can view ...

Using React alongside Three.js and OrbitControls across numerous canvases

I've successfully created a React + Three.js sandbox with multiple canvases displaying simple tetrahedron models. However, I am facing an issue where all instances are using Three.OrbitControls in the same way, causing all models to capture mouse even ...

The Problem of Memory Leakage in AngularJS While Navigating Pages

I am currently working on an AngularJs App with 3 screens. The app is set up to route between these 3 screens every X seconds using the ui-router component. $stateProvider .state("page", { url: "/:pageId/:pageType", template: pageTempl ...

Error: Attempting to access the 'HotelInfo' property of an undefined variable led to an uncaught TypeError

//initiating an AJAX request to access the API jQuery(document).ready(function() { jQuery.ajax({ url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&a ...

In JavaScript, I am looking to duplicate an image and place it back at its original location after it has been moved from its initial position

I am working with 3 draggable images and my objective is to ensure that each image returns to its original position when moved. Ultimately, I want the user to be able to interact with multiple instances of images 1, 2, and 3 on the page, all of which are d ...

Why does my 'click' event listener only work for the first two <li>'s and not the others?

I am new to programming and recently achieved success with my 'click' eventListener. When clicking on the first two li elements within the ul, the class of the div toggles on and off as expected. However, I encountered an issue where clicking on ...

Dual Camera Toggle Functionality with Three.js Orbit Controls

I am facing an issue with two cameras in one scene, one viewport, and one renderer. I switch between cameras using HTML buttons. ISSUES Issue 1 When using camera1, there is no response from moving the mouse. However, when I switch to camera2, the orbit ...

"Bootstrap's modal-backdrop element presents a striking fade effect as it

Issue I am facing a problem related to Bootstrap, specifically with a modal in my HTML file. Whenever I call the modal, it appears with a fade-in effect. The code for my modal: <div class="modal fade" id="exampleModal" tabindex=& ...

How can we prevent other components from re-rendering while using setInterval and updating state within useEffect?

I am working with two components, List.js and Counter.js. In App.js, after the DOM is rendered, I want to use setInterval to display an incremental count every second. Additionally, there is a list that should only update when manually submitted. App.js e ...

Issues encountered while utilizing ncp within my custom grunt extension

Currently, I am working on developing a custom Grunt plugin to copy specific directories based on certain requirements. The aim of this plugin is to allow the user to input a source path via the console as a parameter. Although I am utilizing the ncp modu ...

Simultaneously, two identical messages arrived in the form of push notifications via FCM

I have been working on implementing WebPush notifications using Vue.js and FCM. However, when testing the functionality, I am facing an issue where instead of receiving just one notification from Firebase, TWO IDENTICAL PUSH NOTIFICATIONS are being receive ...

Unraveling the Mystery of Passing Props in React.js

Currently taking an online course to learn React, I encountered a unique scenario where one property is attached to another property in this manner: this.props.property01(this.props.property02) The tutor briefly touched on this code line, leaving me quit ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

To access ES Module, importing is necessary

I'm currently working on a project to develop a service that can convert SVG files into PNG format using the svg2img package. Everything is running smoothly when testing locally with vercel dev, but I keep encountering an error whenever I try to deplo ...