Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut the white part of svg?

Tags:

html

jquery

php

svg

I have a script that generates an SVG image file and other content in the center of the SVG file. Around these images - white background. How can I trim the background? Image sizes in SVG can be different.

Sample — I want to remove white area from svg and leave blue image only.

enter image description here

like image 597
user1062240 Avatar asked Oct 21 '25 04:10

user1062240


1 Answers

Most people around here are looking for the exact opposite of your problem because svg does not allow for setting those background-xxx properties they are familiar with using html. There is no built-in support for backgrounds as you can see from the following snippet where the text inside the div shines through:

div {
    position: absolute;
    top: 50px;
    left: 0px;
}

svg {
    position: absolute;
    top: 20px;
    left: 20px;
    outline: 1px black solid;
}

rect {
    fill: steelblue;
}
<div>
Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

<svg width="300" height="300">
    <rect x="50" y="50" width="200" height="200" />
</svg>

If there is a white background in your svg you will most likely find a fullsize <rect width="100%" height="100%" fill="white"/> or similar providing the background. To get rid of the background you could:

  1. Set fill="none" on your rect.

    <rect width="100%" height="100%" fill="none"/>
    
  2. Remove the <rect> entirely. If you are scripting, however, this will also remove any event listeners attached to it.

like image 116
altocumulus Avatar answered Oct 23 '25 17:10

altocumulus