Is it possible to share a point array or shape between SVG shapes? Can CSS be used to define an SVG shape?

I've scoured the internet looking for a solution to my problem, but nothing seems to work. Is it possible to have multiple SVG shapes share their shape by defining it in one central location? From what I've researched, it looks like SVG shapes can only be defined inline.

For instance:

//shape
<svg class="star" width="12cm" height="4cm" viewBox="0 0 1200 400">
<polygon fill="lime" stroke="blue" stroke-width="10" 
        points="850,75  958,137.5 958,262.5 850,325 742,262.6 742,137.5" />
</svg>
<br>
//same shape
<svg class="star" width="12cm" height="4cm" viewBox="0 0 1200 400">
<polygon fill="lime" stroke="blue" stroke-width="10" 
        points="850,75  958,137.5 958,262.5 850,325 742,262.6 742,137.5" />
</svg>
...

There are many drawbacks to inline definitions like this that I won't even bother listing.

What I'd really like is to do something along these lines:

HTML
<svg class="star"><polygon /></svg><br>
<svg class="star"><polygon /></svg><br>
<svg class="star"><polygon /></svg><br>
<svg class="star"><polygon /></svg><br>
<svg class="star"><polygon /></svg><br>
<svg class="star"><polygon /></svg><br>
...

And then have all the shapes defined in one place, like so.

CSS
.star {
  width: 12cm;
  height: 4cm; 
  viewBox: 0 0 1200 400;
}

.star polygon {
  fill: lime; 
  stroke: blue; 
  stroke-width: 10px; 
  points: [850,75  958,137.5 958,262.5 850,325 742,262.6 742,137.5];
   //I've tried quotes, no quotes, quotes around the numbers.
}

However, despite my attempts and research, nothing has worked so far. I haven't come across any examples or resources that offer alternative methods to defining the points inline.

There must be a more efficient way! Or maybe I just haven't found the correct syntax.

EDIT: The closest thing I've found is this resource on SVG patterns.

Answer №1

Achieving multiple SVGs that share items, such as points or entire image, is definitely possible. One effective technique to accomplish this is using the "use" statement within the SVG code.

To implement this on your page, you can start by adding something similar to the following at the beginning of the body section:

<svg class="star">
 <defs>
  <polygon id="poly1" fill="lime" stroke="blue" stroke-width="10"
   points="850,75  958,137.5 958,262.5 850,325 742,262.6 742,137.5" />
 </defs>
</svg>

After defining the item in the SVG, you can then insert it into the desired location using the following statement:

<svg class="star" viewBox="0 0 1200 400">
 <use xlink:href="#poly1"></use>
</svg>

If you want to include two instances of the same item, simply repeat the use statement within separate SVG containers:

<svg class="star" viewBox="0 0 1200 400">
 <use xlink:href="#poly1"></use>
</svg>
<svg class="star" viewBox="0 0 1200 400">
 <use xlink:href="#poly1"></use>
</svg>

Answer №2

In order to adjust the size of the SVG container using CSS and populate the points in an array or object with JavaScript or JQuery, you can experiment with the demonstration to see if it meets your needs.

$(document).ready(function() {
  var star = $('.star').find('polygon');
  var blob = $('.blob').find('polygon');

  var starObj = {
    points: '850,75  958,137.5 958,262.5 850,325 742,262.6 742,137.5',
    fill: 'lime',
    stroke: 'blue',
    strokeWidth: 10
  };

  var blobObj = {
    points: '800,75  900,137.5 958,262.5 700,325 742,262.6 742,137.5',
    fill: 'lime',
    stroke: 'blue',
    strokeWidth: 50
  };

  star.attr({
    'points': starObj.points,
    'fill': starObj.fill,
    'stroke': starObj.stroke,
    'stroke-width': starObj.strokeWidth
    
  });
  
    blob.attr({
    'points': blobObj.points,
    'fill': blobObj.fill,
    'stroke': blobObj.stroke,
    'stroke-width': blobObj.strokeWidth
    
  });
  
});
.star {
  width: 150px;
  height: 100px;
}
.blob {
  width: 100px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg class="star" viewBox="0 0 1200 400">
  <polygon fill="lime" stroke="blue" stroke-width="10" />
</svg>
<br>

<svg class="blob" viewBox="0 0 1200 400">
  <polygon fill="lime" stroke="blue" stroke-width="10" />
</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

Facebook pages that exceed 700px in length without the need for scrollbars

Is there a way to extend the length of a Facebook page without scrollbars when using an iframe, so that it doesn't crop at 700px? ...

Why is my AngularJS application triggering two events with a single click?

<button id="voterListSearchButton" class="serachButton" ng-click="onSearchButton1Click()">find</button> This button allows users to search for specific information: $scope.onSearchButton1Click = function() { var partId = $("#partIdSearch" ...

Looking to screen usernames that allow for the use of the DOT (.), underscore (_), and Dash (-)?

I am using jQuery to filter usernames that are exactly 3 characters long. The validation criteria includes only allowing the following special characters: ., _, and - var filter = /^[a-zA-Z0-9]+$/; Therefore: if (filter.test(currentval)) { //valid ...

HTML: A peculiar table setup with an image displayed on the right side and text aligned to the left side. Strangely, the

Just starting out and seeking assistance <table style="border:none" cellpadding="0" cellspacing="0"> <tbody> <tr> <td style="border:none" valign="top" vertical-align:"top"; width="20%"> <div><img class= ...

Adjust the height of a DIV element using Jquery Resizable to a minimum height of 1px, smaller than its default value

Having an issue with the Jquery UI Resizable functionality. I've implemented Jquery resizable to adjust a div's width and height dynamically. It's been working well, but I'm encountering a problem when attempting to decrease the height ...

Instructions on integrating a column of buttons into a Bootstrap table containing information retrieved from a MySQL database

My bootstrap table is currently displaying data that is loaded from a MySQL database. I am looking to enhance it by adding a column with buttons, similar to the layout shown in this image. https://i.stack.imgur.com/8fWfR.png However, I am facing some dif ...

When two divs are activated, the third div goes into invisible mode

I attempted this code, but it doesn't appear to be functioning correctly. if(div1)&& (div2)==display:none { div3=display:none; } else { div3=display:block; } ...

What steps can I take to resolve the glitching issue with my progress bar?

There seems to be a problem with the progress bar lagging behind. To see the issue in action, click on THIS LINK and go to the second song. The progress bar appears to be malfunctioning. If you have any solutions or suggestions, please assist! For a visual ...

Raising double-bracket PHP arrays to SQL level

Take a look at this visual representation of my form structure. <div> <input name="address[1][name]" type="text"> <input name="address[1][street]" type="text"> <input name="address[1][city]" type="text"> <input name="address[1][ ...

Error: Unexpected end of argument list in file c:/.../list.ejs during ejs compilation

Hello, I am a beginner in programming and I have been working hard to learn. Unfortunately, I encountered a SyntaxError: missing) after argument list in c://.../list.ejs while compiling ejs error and I am struggling to find the solution. I am reaching out ...

What is a more effective method for presenting text alongside images in a seamless manner?

I'm having trouble aligning two labels of text inline under two images. The images are floating to the right, but when I try to float the text as well, it doesn't align properly underneath them. I attempted to use a separate container for the la ...

Issue: Invalid element type detected: expected a string (for built-in components) or a class/function

Currently, I am in the process of learning how to make API calls using React Redux. I decided to practice by implementing an example in StackBlitz. However, I encountered an error after selecting a channel and clicking on the 'Top News' button. C ...

Upgrading a bootstrap 3 class to bootstrap 4

Can someone help me update the classes col-sm-push-9 and col-sm-pull-3 from bootstrap-3 to bootstrap-4 in the HTML code below? <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width"> <titl ...

Using JavaScript and HTML, create a click event that triggers a drop-down text

Can anyone help me with creating a dropdown feature using JavaScript, HTML, and CSS? I want to be able to click on the name of a project and have information about that project show up. Any suggestions on how I can achieve this? Thanks in advance! ...

Preview Image Unavailable

I am currently working on a project that involves creating a form where users can upload an image and see a preview of it before submitting. Unfortunately, I am facing issues with getting the image preview to display correctly. Below is the HTML code snip ...

Alter the text color once the halfway point is reached at an angle of 175 degrees

I want the text color to turn white when the background color changes to blue after reaching 50% height with a 175 degree angle. Check out this Fiddle .bg { background: linear-gradient(175deg, #e2e2e2 50%, #435289 50%); color:#000; } <div ...

What is the best way to insert text in a TextBox on a webpage using a WebBrowser and then proceed to click a Button on the same site?

Testing out a group link that I recently opened. Check out my group here Here is the code snippet within the constructor: webBrowser1.ScriptErrorsSuppressed = true; webBrowser1.Navigate("https://www.facebook.com/groups/993071237423013/"); Next, in ...

Unable to perform updates for personalized fonts

I've been trying to incorporate custom fonts into my website, but I seem to be facing difficulties in actually implementing them. Could someone please let me know if I am doing it correctly? .pattern{ background:rgba(0,0,0,.5) url(../images/pattern ...

Dynamic content in a CSS animation that rolls credits as they scroll

Currently, I'm working on creating a credit scrolling effect that pulls data from the JustGiving API to display a list of donors. I have successfully populated the list of donors and connected to the API without any issues. However, the challenge lies ...

No feedback received from JSON

Hi, I'm having trouble receiving JSON response using JavaScript. My goal is to display the JSON data as a treeview. index.html: <!DOCTYPE html> <html> <head> <title>JSON VIEW</title> <link href="https:// ...