SVG: What could be causing the shapes inside the svg to not be visible when overlaid on an image?

I am currently working on a project using Angular where my objective is to create a polygon within an image. In order to achieve this, I have placed an SVG element inside the image tag. Both the image and the SVG have fixed width and height dimensions, and the points for the polygon are retrieved from the database with static values. However, I am facing an issue where the polygon does not display correctly. Here is a small example:

https://i.sstatic.net/swbkd.png

Here is the code snippet:

HTML:

<div class="img-map">
    <img #image src="https://content.gnoss.ws/imagenes/Documentos/ImagenesSemanticas/07aabdfa-981f-41f7-828d-78f21adb80a6/eb1d0185-7d5b-4d3a-b84a-5aefd95d3365.jpg" alt=""/>

    <svg style="position:absolute; left:0px; top:0px; width: 100%; height: 100%">
        <polygon class="polygonStyle" [attr.points]="stringPoints" />
    </svg>

</div>

CSS:

.img-map {
  overflow: auto;
  position: relative;
  max-width: calc(100vw - 450px);
}

.polygonStyle {
  stroke: rgba(0, 0, 255, 0.75);
  fill: none;
}

img {
  top: 0;
  left: 0;
  border-radius: 10px;
  height: auto;
  width: 100%;
}

TS:

stringPoints = "1015,481 1043,578 1087,565 1055,467";

I have created a stackblitz to demonstrate the issue. It seems that the problem may be related to scaling, but I am uncertain of how to address it.

Efforts so far:

  • I have come across this question on stackoverflow, but no viable solution was found.
  • This project contains code utilizing the viewbox attribute, yet it does not seem to have any impact. https://i.sstatic.net/3hKE4.png

I am unsure of what mistake I might be making here. Any insights would be greatly appreciated. Thank you!

Answer №1

By default, an SVG has a view box that is 300 x 150 with its origin at 0,0. In the provided examples, the polygon coordinates are: 1015,481 1043,578 1087,565 1055,467. These coordinates fall outside the visible area of the SVG, rendering them invisible.

To rectify this issue, it is recommended to define an explicit view box as follows:

<svg viewBox="1000 400 100 200" style="position:absolute; left:0px; top:0px; width: 100%; height: 100%">
    <polygon class="polygonStyle" [attr.points]="stringPoints" />
</svg>

This code snippet establishes a view box starting at 1000,400 and spanning 100 units by 200 units. The SVG content will then be adjusted and scaled so that all coordinates falling between 1000-1100 on the x-axis and 400-600 on the y-axis are within the visible area of the SVG.

In essence, the viewBox attribute directly impacts the visibility of SVG content, while attributes like width, height, and position dictate where and how large the SVG is displayed.

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

Utilizing class attributes within multiple classes

I have created a custom class called MutationValidator as follows: const ERR_MSG = 'Error1'; @Service() export class MutationValidator { .. } This class is used in another class like so: import { MutationValidator } from './mutation ...

Angular 2: A guide to dynamically adding and updating meta tags through a component, similar to the title service functionality

As someone who is just beginning to explore Angular 2, I find myself in need of setting up meta tags such as og: description and others directly from a component. I am unsure of how to dynamically update these meta tags or add new ones to the index.html fr ...

Using Typescript and React to assign an array object to state

Here is the situation: const [state, setState] = useState({ menuCatalog: true, menuCommon: true, fetched_data: [] }); An example of data I am trying to set to the state property "fetched_data" looks like this: [{"id": 1, "name": "some_name", " ...

What are the steps to making request and response models in Angular?

Exploring the best approach for handling request and response models in Angular prompts the question of whether we should always create separate models for GET and POST operations, or if utilizing keywords like partial could offer a solution. For example, ...

Optional parameters in typed languages can either have zero or all parameters provided

I am delving into the world of typed functional programming and have embarked on implementing partial application with a focus on type safety. Issue at hand: I'm aiming to create a function that can take a function along with zero or all of its param ...

Typescript threw an error: Zod was anticipating a string, but instead it got

I am encountering a Zod error multiple times while attempting to submit my req.body data to the Prisma ORM using Insomnia: ZodError: [ { "code": "invalid_type", "expected": "string", "received" ...

Component's mocking service is being ignored

I am currently exploring how to simulate a service (specifically one that makes http calls) in order to test a component. @Component({ selector: 'ub-funding-plan', templateUrl: './funding-plan.component.html', styleUrls: ['. ...

Issue TS2349 occurs when attempting to use a combination of boolean and function types within union typing

In my class, there is a property called "isVisible" which can be either a boolean value or a function that returns a boolean. The code snippet below demonstrates what I am currently using. It works fine and achieves the desired result, but during compilat ...

Tips for obtaining the most recent HTML element in Angular

I was able to include HTML content in an Angular (7) UI using the DomSanitizer this.sanitizer.bypassSecurityTrustHtml("htmlstr") Once the content is sanitized and displayed in the HTML view, users have the ability to modify the values as desired ...

After being awaited recursively, the resolved promise does not perform any actions

When working with the Twitter API, I need to make recursive method calls to retrieve tweets since each request only returns a maximum of 100 tweets. The process is straightforward: Call the function and await it Make an HTTP request and await that If the ...

Changing the Month Label Format from Short (MMM) to Long (MMMM) in Angular Material Datepicker

I am looking to customize the month labels in Angular Material datepicker. By default, the month view displays in MMM format and I want to change it to MMMM using custom MatDateFormats. export const APP_DATE_FORMATS: MatDateFormats = { parse: { dat ...

Creating a contravariant function member in TypeScript?

I am facing a challenge with a class that contains a member which is a function taking an instance of the same class: class Super { public member: (x: Super) => void = function(){} use() {const f = this.member; f(this)} } However, I need the me ...

Angular - Brilliant time selection tool (BTS) The TimePicker feature fails to automatically switch to selecting minutes after choosing the hour

I'm currently implementing the Amazing time picker in my app and I'm facing an issue where it doesn't automatically switch to minutes after selecting the hour. component.html <input type="time" atp-time-picker formControlName="time" cla ...

Can TypeScript support the implementation of versatile decorators that can be linked together based on their input and output types?

Within our integration processes, we have developed templated implementations in our codebase that align well with the "pipe and filter" pattern in my opinion. These "components" can be structured in the following formats: class Component1<In, Out, Xi ...

NextJS function utilizes its own references within React and automatically fetches data without the need for an import

I recently purchased this template and I'm trying to figure out which page the code snippet "{getLayout(<Component {...pageProps} />)}" is directed to during the initial load. It seems like it might be a global variable hidden somewher ...

Example showcasing the functionality of the react-custom-scrollbars package in a TypeScript React application

In my TypeScript React project, I am struggling to set up the react-custom-scrollbars package successfully. Despite consulting the examples provided in the GitHub repository, I have not been able to get it working. Can someone share a functional example ...

Imitate dependencies using Mocha and Typescript

In my typescript project, I am using mocha. Let's consider two modules: // http.ts export class Http { } // app.ts import Http from './http'; export class App { } I want to know how to mock the Http module while testing the App. The te ...

How to Integrate FullCalendar with Your Angular Application

Having some confusion with installing Fullcalendar in my Angular 8 project. I followed the instructions on the Fullcalendar website and installed the package under @fullcalendar using npm install --save @fullcalendar/angular, but then came across examples ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

Angular Material Date Time Selector

I'm having trouble integrating a date time picker in an Angular Material form. Here's the code I am using: <mat-form-field> <input formControlName="nextScheduledDate" mdc-datetime-picker="" date="true" time="true" type="text" id="date ...