Apply SVG Filter to HTML5 Canvas? - html

Objective: Apply CSS Filters to video using html5 and JavaScript.
Contraints: The solution must be compatible with Internet Exporer 10 (for Windows 8). I am really making a Metro app.
So Far:
I have a <video> that I am pumping onto a <canvas>. I thought I would be able to apply CSS filters directly to this (e.g. invert or brightness) but it turns out those are not compatible with IE10.
Thoughts: I am hoping for a way to apply SVG filters to the canvas. Is this possible? Do I need to copy the <canvas> to an <image> and apply the filters to that? Alternatively, should there be a way to wrap the canvas in a <foreignObject>?
Thank you for all your help!
Here is some code for those interested:
filters.svg:
<?xml version="1.0" standalone="no"?>
<svg width="1" height="1" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<filter id="blur">
<feGaussianBlur in="SourceGraphic" stdDeviation="2 3" />
</filter>
</defs>
</svg>
style.css:
.a {
filter: url(filter.svg#blur);
-ms-transform: matrix(-1, 0, 0, 1, 0, 0);
}
page.html:
<div class="itemtemplate" data-win-control="WinJS.Binding.Template">
<canvas class="a" style="width: 180px;height:180px;margin-bottom: -5px;" data-win-bind="style.backgroundColor: bc; id: effectId" />
</div>
The Following Code Works, albeit very slowly, to accomplish my goal. Thank you, Anthony!
<html>
<head>
</head>
<body>
<svg id="svgroot" viewbox="0 0 800 800" width="800" height="800" preserveAspectRatio="xMidYMin">
<defs>
<filter id="myHueRotate">
<feColorMatrix type="hueRotate" values="270"/>
</filter>
</defs>
<image id="a" filter="url(#myHueRotate)" x="0" y="0" width="300" height="300" />
<image id="b" filter="url(#myHueRotate)" x="300" y="0" width="300" height="300" />
<image id="c" filter="url(#myHueRotate)" x="0" y="300" width="300" height="300" />
<image id="d" filter="url(#myHueRotate)" x="300" y="300" width="300" height="300" />
</svg>
<canvas id="canvas" height="300" width="300"></canvas>
<video id="vid" src="movie.m4v" height="300" width="300" style="display: none" autoplay/>
<script>
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'img.jpg';
img.onload = function(){
//ctx.drawImage(img,0,0);
//var canvasImage = canvas.toDataURL("image/png");
//var svgImage = document.getElementById('a');
//svgImage.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", canvasImage);
draw();
}
img.load();
function draw(){
var ctx = document.getElementById('canvas').getContext('2d');
var vid = document.getElementById('vid')
ctx.drawImage(vid,0,0,300,300);
var canvasImage = canvas.toDataURL("image/png");
document.getElementById('a').setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", canvasImage);
document.getElementById('b').setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", canvasImage);
document.getElementById('c').setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", canvasImage);
document.getElementById('d').setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", canvasImage);
setTimeout(draw,40);
}
</script>
</body>
</html>

First, articles to read:
moving-to-standards-based-web-graphics-in-ie10
Notice specifically the sections:
Use SVG, not VML
and
Use CSS3, not DX Filters
In that second section, they mention:
DX Filters are not the same as SVG Filter Effects, though both use the CSS property name filter.
Second article:
Introduction to Filters and Transitions
They give a specific example of how to use invert, but, assuming it is the way in IE, I can see why it wasn't easy to find and may or may not work in your case. But the css would be:
#yourTargetElement {
filter: DXImageTransform.Microsoft.BasicImage(invert=1);
}
They don't mention brightness, but they do mention several other filters and transitions, and that first article does mention using SVG. More details (hopefully helpful ones) at:
SVG Filter Effects in IE10
This looks like part 1 of the key:
A filter is applied to an SVG element via the filter attribute, in the form of filter="url(#filterId)", or it can be applied as a CSS property filter:url(#filterId)
And this is part 2:
There are 16 different filter primitives.
Now, I believe the 16 they refer to are the full set for SVG, but knowing MS, it could also mean either:
These are the 16 we support, or
These are the 16 we've invented so as to continue our claim to make IE standards-compliant and SVG/MathML friendly, but making it harder than it would be in any other browser...because we can.
Or, to quote Lily Tomlin: "We don't care, we don't have to...we're the phone company."
But, assuming MS is finally realizing they need to catch up, reading further on the 16 primitive filters, supposedly you just have your embedded SVG, with the filters in the right place (defs) and call them via css. Here is one of their examples (slightly modified and simplified by me):
HTML w/ Embedded SVG:
<div id="svg_wrapper">
<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 800 533" preserveAspectRatio="xMidYMin">
<defs>
<filter id="filtersPicture">
<feComposite operator="arithmetic" k1="0" k2="1" k3="0" k4="0"
in="SourceGraphic" in2="SourceGraphic" result="inputTo_6">
</feComposite>
<feColorMatrix type="saturate" id="filter_6" values="2"
data-filterId="6">
</feColorMatrix>
</filter>
</svg>
</div>
CSS (They use JS to make it dynamic, so beware):
<style type="text/css">
#yourTargetElement{
filter:url(#filtersPicture);
}
</style>
The reason I caution on how "easy" they make it look is because they are adding the style via js and an interactive form (maybe you have the same thing in mind), but I imagine that runs the same risk as calling an element in a script before it is in the DOM, in that it can't find the filter and throws an error. So be sure if you want to keep it simple (non-dynamic) and things still aren't working, to try putting the filter/svg above the style (even if this causes a flicker).

Related

rect's stroke doesn't follow the rect's radius [duplicate]

Currently building a browser-based SVG application. Within this app, various shapes can be styled and positioned by the user, including rectangles.
When I apply a stroke-width to an SVG rect element of say 1px, the stroke is applied to the rect’s offset and inset in different ways by different browsers. This is proving to be troublesome, especially when I try to calculate the outer width and visual position of a rectangle and position it next to other elements.
For example:
Firefox adds 1px inset (bottom and left), and 1px offset (top and right)
Chrome adds 1px inset (top and left), and 1px offset (bottom and right)
My only solution so far would be to draw the actual borders myself (probably with the path tool) and position the borders behind the stroked element. But this solution is an unpleasant workaround, and I’d prefer not to go down this road if possible.
So my question is, can you control how an SVG’s stroke-width is drawn on elements?
No, you cannot specify whether the stroke is drawn inside or outside an element. I made a proposal to the SVG working group for this functionality in 2003, but it received no support (or discussion).
As I noted in the proposal,
you can achieve the same visual result as "inside" by doubling your stroke width and then using a clipping path to clip the object to itself, and
you can achieve the same visual result as 'outside' by doubling the stroke width and then overlaying a no-stroke copy of the object on top of itself.
Edit: This answer may be wrong in the future. It should be possible to achieve these results using SVG Vector Effects, by combining veStrokePath with veIntersect (for 'inside') or with veExclude (for 'outside). However, Vector Effects are still a working draft module with no implementations that I can yet find.
Edit 2: The SVG 2 draft specification includes a stroke-alignment property (with center|inside|outside possible values). This property may make it into UAs eventually.
Edit 3: Amusingly and dissapointingly, the SVG working group has removed stroke-alignment from SVG 2. You can see some of the concerns described after the prose here.
UPDATE: The stroke-alignment attribute was on April 1st, 2015 moved to a completely new spec called SVG Strokes.
As of the SVG 2.0 Editor’s Draft of February 26th, 2015 (and possibly since February 13th), the stroke-alignment property is present with the values inner, center (default) and outer.
It seems to work the same way as the stroke-location property proposed by #Phrogz and the later stroke-position suggestion. This property has been planned since at least 2011, but apart from an annotation that said
SVG 2 shall include a way to specify stroke position
, it has never been detailed in the spec as it was deferred - until now, it seems.
No browser support this property, or, as far as I know, any of the new SVG 2 features, yet, but hopefully they will soon as the spec matures. This has been a property I personally have been urging to have, and I'm really happy that it's finally there in the spec.
There seems to be some issues as to how to the property should behave on open paths as well as loops. These issues will, most probably, prolong implementations across browsers. However, I will update this answer with new information as browsers begin to support this property.
I found an easy way, which has a few restrictions, but worked for me:
define the shape in defs
define a clip path referencing the shape
use it and double the stroke with as the outside is clipped
Here a working example:
<svg width="240" height="240" viewBox="0 0 1024 1024">
<defs>
<path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>
<clipPath id="clip">
<use xlink:href="#ld"/>
</clipPath>
</defs>
<g>
<use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="#00D2B8" clip-path="url(#clip)"/>
</g>
</svg>
You can use CSS to style the order of stroke and fills. That is, stroke first and then fill second, and get the desired effect.
MDN on paint-order: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/paint-order
CSS code:
paint-order: stroke;
Here's a function that will calculate how many pixels you need to add - using the given stroke - to the top, right, bottom and left, all based on the browser:
var getStrokeOffsets = function(stroke){
var strokeFloor = Math.floor(stroke / 2), // max offset
strokeCeil = Math.ceil(stroke / 2); // min offset
if($.browser.mozilla){ // Mozilla offsets
return {
bottom: strokeFloor,
left: strokeFloor,
top: strokeCeil,
right: strokeCeil
};
}else if($.browser.webkit){ // WebKit offsets
return {
bottom: strokeCeil,
left: strokeFloor,
top: strokeFloor,
right: strokeCeil
};
}else{ // default offsets
return {
bottom: strokeCeil,
left: strokeCeil,
top: strokeCeil,
right: strokeCeil
};
}
};
As people above have noted you'll either have to recalculate an offset to the stroke's path coordinates or double its width and then mask one side or the other, because not only does SVG not natively support Illustrator's stroke alignment, but PostScript doesn't either.
The specification for strokes in Adobe's PostScript Manual 2nd edition states:
"4.5.1 Stroking:
The stroke operator draws a line of some thickness along the current path. For each straight or curved segment in the path, stroke draws a line that is centered on the segment with sides parallel to the segment." (emphasis theirs)
The rest of the specification has no attributes for offsetting the line's position. When Illustrator lets you align inside or outside, it's recalculating the actual path's offset (because it's still computationally cheaper than overprinting then masking). The path coordinates in the .ai document are reference, not what gets rastered or exported to a final format.
Because Inkscape's native format is spec SVG, it can't offer a feature the spec lacks.
Here is a work around for inner bordered rect using symbol and use.
Example: https://jsbin.com/yopemiwame/edit?html,output
SVG:
<svg>
<symbol id="inner-border-rect">
<rect class="inner-border" width="100%" height="100%" style="fill:rgb(0,255,255);stroke-width:10;stroke:rgb(0,0,0)">
</symbol>
...
<use xlink:href="#inner-border-rect" x="?" y="?" width="?" height="?">
</svg>
Note: Make sure to replace the ? in use with real values.
Background: The reason why this works is because symbol establishes a new viewport by replacing symbol with svg and creating an element in the shadow DOM. This svg of the shadow DOM is then linked into your current SVG element. Note that svgs can be nested and every svg creates a new viewport, which clips everything that overlaps, including the overlapping border. For a much more detailed overview of whats going on read this fantastic article by Sara Soueidan.
I don’t know how helpful will that be but in my case I just created another circle with border only and placed it “inside” the other shape.
This worked for me:
.btn {
border: 1px solid black;
box-shadow: inset 0 0 0 1px black;
}
A (dirty) possible solution is by using patterns,
here is an example with an inside stroked triangle :
https://jsfiddle.net/qr3p7php/5/
<style>
#triangle1{
fill: #0F0;
fill-opacity: 0.3;
stroke: #000;
stroke-opacity: 0.5;
stroke-width: 20;
}
#triangle2{
stroke: #f00;
stroke-opacity: 1;
stroke-width: 1;
}
</style>
<svg height="210" width="400" >
<pattern id="fagl" patternUnits="objectBoundingBox" width="2" height="1" x="-50%">
<path id="triangle1" d="M150 0 L75 200 L225 200 Z">
</pattern>
<path id="triangle2" d="M150 0 L75 200 L225 200 Z" fill="url(#fagl)"/>
</svg>
The solution from Xavier Ho of doubling the width of the stroke and changing the paint-order is brilliant, although only works if the fill is a solid color, with no transparency.
I have developed other approach, more complicated but works for any fill. It also works in ellipses or paths (with the later there are some corner cases with strange behaviour, for example open paths that crosses theirselves, but not much).
The trick is to display the shape in two layers. One without stroke (only fill), and another one only with stroke at double width (transparent fill) and passed through a mask that shows the whole shape, but hides the original shape without stroke.
<svg width="240" height="240" viewBox="0 0 1024 1024">
<defs>
<path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>
<mask id="mask">
<use xlink:href="#ld" stroke="#FFFFFF" stroke-width="160" fill="#FFFFFF"/>
<use xlink:href="#ld" fill="#000000"/>
</mask>
</defs>
<g>
<use xlink:href="#ld" fill="#00D2B8"/>
<use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="red" mask="url(#mask)"/>
</g>
</svg>
The easiest way I found is to add clip-path into circle
Add clip-path="circle()"
<circle id="circle" clip-path="circle()" cx="100" cy="100" r="100" fill="none" stroke="currentColor" stroke-width="5" />
Then the stroke-width="5" will magically become inner 5px stroke with absolute 100px radius.
Update 2023: The current draft renamed the attribute to stroke-align
Browser Support 2023:
See caniuse
This CSS property is not supported in any modern browser, nor are
there any known plans to support it.
Polyfill-like helper function
Based on the previous approaches to combine paint-order, mask and clip-path.
(As suggested by #Xavier Ho
#Jorg Janke)
//emulateStrokeAlign();
function emulateStrokeAlign() {
let supportsSvgStrokeAlign = CSS.supports("stroke-align", "outer") ?
true :
CSS.supports("stroke-alignment", "outer") ?
true :
false;
console.log("supportsSvgStrokeAlign", supportsSvgStrokeAlign);
if (!supportsSvgStrokeAlign) {
let ns = "http://www.w3.org/2000/svg";
let strokeAlignmentEls = document.querySelectorAll(
"*[stroke-alignment], *[stroke-align]"
);
strokeAlignmentEls.forEach((el, s) => {
let svg = el.closest("svg");
// set auto ids to prevent non-unique mask ids
let svgID = svg.id ? svg.id : "svg_" + s;
svg.id = svgID;
//create <defs> if not previously appended
let defs = svg.querySelector("defs");
if (!defs) {
defs = document.createElementNS(ns, "defs");
svg.insertBefore(defs, svg.children[0]);
}
let style = window.getComputedStyle(el);
let strokeWidth = parseFloat(style.strokeWidth);
let strokeAlignment = el.getAttribute("stroke-alignment") ?
el.getAttribute("stroke-alignment") :
el.getAttribute("stroke-align");
el.removeAttribute("stroke-align");
el.removeAttribute("stroke-alignment");
el.setAttribute("data-stroke-align", strokeAlignment);
let maskClipId = `mask-${svgID}-${s}`;
if (strokeAlignment === "outer") {
// create mask
let mask = document.createElementNS(ns, "mask");
mask.id = maskClipId;
let maskEl = el.cloneNode();
mask.appendChild(maskEl);
defs.appendChild(mask);
maskEl.setAttribute("fill", "#000");
mask.setAttribute("maskUnits", "userSpaceOnUse");
maskEl.setAttribute("stroke", "#fff");
maskEl.removeAttribute("stroke-opacity");
maskEl.removeAttribute("id");
maskEl.setAttribute("paint-order", "stroke");
maskEl.style.strokeWidth = strokeWidth * 2;
// clone stroke
let cloneStroke = el.cloneNode();
cloneStroke.style.fill = "none";
cloneStroke.style.strokeWidth = strokeWidth * 2;
cloneStroke.removeAttribute("id");
cloneStroke.removeAttribute("stroke-alignment");
cloneStroke.classList.add("cloneStrokeOuter");
cloneStroke.setAttribute("mask", `url(#${maskClipId})`);
el.parentNode.insertBefore(cloneStroke, el.nextElementSibling);
//remove stroke from original element
el.style.stroke = "none";
}
if (strokeAlignment === "inner") {
//create clipPath
let clipPathEl = el.cloneNode();
let clipPath = document.createElementNS(ns, "clipPath");
clipPath.id = maskClipId;
defs.appendChild(clipPath);
clipPathEl.removeAttribute("id");
clipPath.appendChild(clipPathEl);
el.setAttribute("clip-path", `url(#${maskClipId})`);
el.style.strokeWidth = strokeWidth * 2;
}
});
}
}
body {
margin: 2em;
}
svg {
width: 100%;
height: auto;
overflow: visible;
border: 1px solid #ccc;
}
body {
margin: 2em;
}
svg {
height: 20em;
overflow: visible;
border: 1px solid #ccc;
}
<p><button onclick="emulateStrokeAlign()">Emulate stroke align</button></p>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 380 120">
<g id="myGroup" style="fill:rgb(45, 130, 255); stroke:#000; stroke-width:10; stroke-opacity:1;">
<rect id="el1" stroke-alignment="outer" x="10" y="10" width="100" height="100" />
<rect id="el2" x="140" y="10" width="100" height="100" />
<rect id="el3" stroke-alignment="inner" x="270" y="10" width="100" height="100" />
</g>
</svg>
<svg viewBox="0 0 12 6" xmlns="http://www.w3.org/2000/svg" stroke-width="0.5">
<path d="M1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5z" fill="blue" stroke-align="outer" stroke="red" stroke-opacity="0.5" stroke-linecap="butt" />
<path d="M7,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5z" fill="blue" stroke-align="inner" stroke="red" stroke-opacity="0.5" />
</svg>
Hardcoded offset via paper.js offset glenzli's plugin
This approach will actually grow/shrink your <path> elements to get the desired stroke position (using the default middle stroke-alignment).
const canvas = document.createElement("canvas");
canvas.style.display='none';
document.body.appendChild(canvas);
//const canvas = document.querySelector("canvas");
paper.setup(canvas);
let strokeEls = document.querySelectorAll("*[stroke-alignment]");
strokeEls.forEach((el,i) => {
let type = el.nodeName;
let style = window.getComputedStyle(el);
let strokeWidth = parseFloat(style.strokeWidth);
let strokeAlignment = el.getAttribute('stroke-alignment');
let offset = strokeAlignment==='outer' ? strokeWidth/2 : (strokeAlignment==='inner' ? strokeWidth / -2 : 0);
// convert primitive
if(type!=='path'){
el = convertPrimitiveToPath(el);
}
let d = el.getAttribute("d");
let polyPath = new paper.Path(el.getAttribute("d"));
let dOffset = offset ? PaperOffset.offset(polyPath, offset)
.exportSVG()
.getAttribute("d") : d;
el.setAttribute("d", dOffset);
});
body{
margin:2em;
}
svg{
width:100%;
overflow:visible;
border:1px solid #ccc;
}
<svg viewBox="0 0 12 6" xmlns="http://www.w3.org/2000/svg" stroke-width="0.5">
<path d="M1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" stroke="black" fill="none" stroke-linejoin="miter"/>
<path d="M1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" fill="none" stroke-linejoin="miter" stroke-alignment="outer" stroke="red" stroke-opacity="0.5" />
<path d="M7,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" stroke="black" fill="none" stroke-linejoin="round" />
<path d="M7,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" fill="none" stroke-linejoin="round" stroke-alignment="inner" stroke="red" stroke-opacity="0.5" />
</svg>
<script src="https://unpkg.com/paper#0.12.15/dist/paper-full.min.js"></script>
<script src="https://unpkg.com/paperjs-offset#1.0.8/dist/paperjs-offset.js"></script>
However, the library struggles with complex shapes.

SVG outer alignment of semi transparent stroke [duplicate]

Currently building a browser-based SVG application. Within this app, various shapes can be styled and positioned by the user, including rectangles.
When I apply a stroke-width to an SVG rect element of say 1px, the stroke is applied to the rect’s offset and inset in different ways by different browsers. This is proving to be troublesome, especially when I try to calculate the outer width and visual position of a rectangle and position it next to other elements.
For example:
Firefox adds 1px inset (bottom and left), and 1px offset (top and right)
Chrome adds 1px inset (top and left), and 1px offset (bottom and right)
My only solution so far would be to draw the actual borders myself (probably with the path tool) and position the borders behind the stroked element. But this solution is an unpleasant workaround, and I’d prefer not to go down this road if possible.
So my question is, can you control how an SVG’s stroke-width is drawn on elements?
No, you cannot specify whether the stroke is drawn inside or outside an element. I made a proposal to the SVG working group for this functionality in 2003, but it received no support (or discussion).
As I noted in the proposal,
you can achieve the same visual result as "inside" by doubling your stroke width and then using a clipping path to clip the object to itself, and
you can achieve the same visual result as 'outside' by doubling the stroke width and then overlaying a no-stroke copy of the object on top of itself.
Edit: This answer may be wrong in the future. It should be possible to achieve these results using SVG Vector Effects, by combining veStrokePath with veIntersect (for 'inside') or with veExclude (for 'outside). However, Vector Effects are still a working draft module with no implementations that I can yet find.
Edit 2: The SVG 2 draft specification includes a stroke-alignment property (with center|inside|outside possible values). This property may make it into UAs eventually.
Edit 3: Amusingly and dissapointingly, the SVG working group has removed stroke-alignment from SVG 2. You can see some of the concerns described after the prose here.
UPDATE: The stroke-alignment attribute was on April 1st, 2015 moved to a completely new spec called SVG Strokes.
As of the SVG 2.0 Editor’s Draft of February 26th, 2015 (and possibly since February 13th), the stroke-alignment property is present with the values inner, center (default) and outer.
It seems to work the same way as the stroke-location property proposed by #Phrogz and the later stroke-position suggestion. This property has been planned since at least 2011, but apart from an annotation that said
SVG 2 shall include a way to specify stroke position
, it has never been detailed in the spec as it was deferred - until now, it seems.
No browser support this property, or, as far as I know, any of the new SVG 2 features, yet, but hopefully they will soon as the spec matures. This has been a property I personally have been urging to have, and I'm really happy that it's finally there in the spec.
There seems to be some issues as to how to the property should behave on open paths as well as loops. These issues will, most probably, prolong implementations across browsers. However, I will update this answer with new information as browsers begin to support this property.
I found an easy way, which has a few restrictions, but worked for me:
define the shape in defs
define a clip path referencing the shape
use it and double the stroke with as the outside is clipped
Here a working example:
<svg width="240" height="240" viewBox="0 0 1024 1024">
<defs>
<path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>
<clipPath id="clip">
<use xlink:href="#ld"/>
</clipPath>
</defs>
<g>
<use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="#00D2B8" clip-path="url(#clip)"/>
</g>
</svg>
You can use CSS to style the order of stroke and fills. That is, stroke first and then fill second, and get the desired effect.
MDN on paint-order: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/paint-order
CSS code:
paint-order: stroke;
Here's a function that will calculate how many pixels you need to add - using the given stroke - to the top, right, bottom and left, all based on the browser:
var getStrokeOffsets = function(stroke){
var strokeFloor = Math.floor(stroke / 2), // max offset
strokeCeil = Math.ceil(stroke / 2); // min offset
if($.browser.mozilla){ // Mozilla offsets
return {
bottom: strokeFloor,
left: strokeFloor,
top: strokeCeil,
right: strokeCeil
};
}else if($.browser.webkit){ // WebKit offsets
return {
bottom: strokeCeil,
left: strokeFloor,
top: strokeFloor,
right: strokeCeil
};
}else{ // default offsets
return {
bottom: strokeCeil,
left: strokeCeil,
top: strokeCeil,
right: strokeCeil
};
}
};
As people above have noted you'll either have to recalculate an offset to the stroke's path coordinates or double its width and then mask one side or the other, because not only does SVG not natively support Illustrator's stroke alignment, but PostScript doesn't either.
The specification for strokes in Adobe's PostScript Manual 2nd edition states:
"4.5.1 Stroking:
The stroke operator draws a line of some thickness along the current path. For each straight or curved segment in the path, stroke draws a line that is centered on the segment with sides parallel to the segment." (emphasis theirs)
The rest of the specification has no attributes for offsetting the line's position. When Illustrator lets you align inside or outside, it's recalculating the actual path's offset (because it's still computationally cheaper than overprinting then masking). The path coordinates in the .ai document are reference, not what gets rastered or exported to a final format.
Because Inkscape's native format is spec SVG, it can't offer a feature the spec lacks.
Here is a work around for inner bordered rect using symbol and use.
Example: https://jsbin.com/yopemiwame/edit?html,output
SVG:
<svg>
<symbol id="inner-border-rect">
<rect class="inner-border" width="100%" height="100%" style="fill:rgb(0,255,255);stroke-width:10;stroke:rgb(0,0,0)">
</symbol>
...
<use xlink:href="#inner-border-rect" x="?" y="?" width="?" height="?">
</svg>
Note: Make sure to replace the ? in use with real values.
Background: The reason why this works is because symbol establishes a new viewport by replacing symbol with svg and creating an element in the shadow DOM. This svg of the shadow DOM is then linked into your current SVG element. Note that svgs can be nested and every svg creates a new viewport, which clips everything that overlaps, including the overlapping border. For a much more detailed overview of whats going on read this fantastic article by Sara Soueidan.
I don’t know how helpful will that be but in my case I just created another circle with border only and placed it “inside” the other shape.
This worked for me:
.btn {
border: 1px solid black;
box-shadow: inset 0 0 0 1px black;
}
A (dirty) possible solution is by using patterns,
here is an example with an inside stroked triangle :
https://jsfiddle.net/qr3p7php/5/
<style>
#triangle1{
fill: #0F0;
fill-opacity: 0.3;
stroke: #000;
stroke-opacity: 0.5;
stroke-width: 20;
}
#triangle2{
stroke: #f00;
stroke-opacity: 1;
stroke-width: 1;
}
</style>
<svg height="210" width="400" >
<pattern id="fagl" patternUnits="objectBoundingBox" width="2" height="1" x="-50%">
<path id="triangle1" d="M150 0 L75 200 L225 200 Z">
</pattern>
<path id="triangle2" d="M150 0 L75 200 L225 200 Z" fill="url(#fagl)"/>
</svg>
The solution from Xavier Ho of doubling the width of the stroke and changing the paint-order is brilliant, although only works if the fill is a solid color, with no transparency.
I have developed other approach, more complicated but works for any fill. It also works in ellipses or paths (with the later there are some corner cases with strange behaviour, for example open paths that crosses theirselves, but not much).
The trick is to display the shape in two layers. One without stroke (only fill), and another one only with stroke at double width (transparent fill) and passed through a mask that shows the whole shape, but hides the original shape without stroke.
<svg width="240" height="240" viewBox="0 0 1024 1024">
<defs>
<path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>
<mask id="mask">
<use xlink:href="#ld" stroke="#FFFFFF" stroke-width="160" fill="#FFFFFF"/>
<use xlink:href="#ld" fill="#000000"/>
</mask>
</defs>
<g>
<use xlink:href="#ld" fill="#00D2B8"/>
<use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="red" mask="url(#mask)"/>
</g>
</svg>
The easiest way I found is to add clip-path into circle
Add clip-path="circle()"
<circle id="circle" clip-path="circle()" cx="100" cy="100" r="100" fill="none" stroke="currentColor" stroke-width="5" />
Then the stroke-width="5" will magically become inner 5px stroke with absolute 100px radius.
Update 2023: The current draft renamed the attribute to stroke-align
Browser Support 2023:
See caniuse
This CSS property is not supported in any modern browser, nor are
there any known plans to support it.
Polyfill-like helper function
Based on the previous approaches to combine paint-order, mask and clip-path.
(As suggested by #Xavier Ho
#Jorg Janke)
//emulateStrokeAlign();
function emulateStrokeAlign() {
let supportsSvgStrokeAlign = CSS.supports("stroke-align", "outer") ?
true :
CSS.supports("stroke-alignment", "outer") ?
true :
false;
console.log("supportsSvgStrokeAlign", supportsSvgStrokeAlign);
if (!supportsSvgStrokeAlign) {
let ns = "http://www.w3.org/2000/svg";
let strokeAlignmentEls = document.querySelectorAll(
"*[stroke-alignment], *[stroke-align]"
);
strokeAlignmentEls.forEach((el, s) => {
let svg = el.closest("svg");
// set auto ids to prevent non-unique mask ids
let svgID = svg.id ? svg.id : "svg_" + s;
svg.id = svgID;
//create <defs> if not previously appended
let defs = svg.querySelector("defs");
if (!defs) {
defs = document.createElementNS(ns, "defs");
svg.insertBefore(defs, svg.children[0]);
}
let style = window.getComputedStyle(el);
let strokeWidth = parseFloat(style.strokeWidth);
let strokeAlignment = el.getAttribute("stroke-alignment") ?
el.getAttribute("stroke-alignment") :
el.getAttribute("stroke-align");
el.removeAttribute("stroke-align");
el.removeAttribute("stroke-alignment");
el.setAttribute("data-stroke-align", strokeAlignment);
let maskClipId = `mask-${svgID}-${s}`;
if (strokeAlignment === "outer") {
// create mask
let mask = document.createElementNS(ns, "mask");
mask.id = maskClipId;
let maskEl = el.cloneNode();
mask.appendChild(maskEl);
defs.appendChild(mask);
maskEl.setAttribute("fill", "#000");
mask.setAttribute("maskUnits", "userSpaceOnUse");
maskEl.setAttribute("stroke", "#fff");
maskEl.removeAttribute("stroke-opacity");
maskEl.removeAttribute("id");
maskEl.setAttribute("paint-order", "stroke");
maskEl.style.strokeWidth = strokeWidth * 2;
// clone stroke
let cloneStroke = el.cloneNode();
cloneStroke.style.fill = "none";
cloneStroke.style.strokeWidth = strokeWidth * 2;
cloneStroke.removeAttribute("id");
cloneStroke.removeAttribute("stroke-alignment");
cloneStroke.classList.add("cloneStrokeOuter");
cloneStroke.setAttribute("mask", `url(#${maskClipId})`);
el.parentNode.insertBefore(cloneStroke, el.nextElementSibling);
//remove stroke from original element
el.style.stroke = "none";
}
if (strokeAlignment === "inner") {
//create clipPath
let clipPathEl = el.cloneNode();
let clipPath = document.createElementNS(ns, "clipPath");
clipPath.id = maskClipId;
defs.appendChild(clipPath);
clipPathEl.removeAttribute("id");
clipPath.appendChild(clipPathEl);
el.setAttribute("clip-path", `url(#${maskClipId})`);
el.style.strokeWidth = strokeWidth * 2;
}
});
}
}
body {
margin: 2em;
}
svg {
width: 100%;
height: auto;
overflow: visible;
border: 1px solid #ccc;
}
body {
margin: 2em;
}
svg {
height: 20em;
overflow: visible;
border: 1px solid #ccc;
}
<p><button onclick="emulateStrokeAlign()">Emulate stroke align</button></p>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 380 120">
<g id="myGroup" style="fill:rgb(45, 130, 255); stroke:#000; stroke-width:10; stroke-opacity:1;">
<rect id="el1" stroke-alignment="outer" x="10" y="10" width="100" height="100" />
<rect id="el2" x="140" y="10" width="100" height="100" />
<rect id="el3" stroke-alignment="inner" x="270" y="10" width="100" height="100" />
</g>
</svg>
<svg viewBox="0 0 12 6" xmlns="http://www.w3.org/2000/svg" stroke-width="0.5">
<path d="M1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5z" fill="blue" stroke-align="outer" stroke="red" stroke-opacity="0.5" stroke-linecap="butt" />
<path d="M7,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5z" fill="blue" stroke-align="inner" stroke="red" stroke-opacity="0.5" />
</svg>
Hardcoded offset via paper.js offset glenzli's plugin
This approach will actually grow/shrink your <path> elements to get the desired stroke position (using the default middle stroke-alignment).
const canvas = document.createElement("canvas");
canvas.style.display='none';
document.body.appendChild(canvas);
//const canvas = document.querySelector("canvas");
paper.setup(canvas);
let strokeEls = document.querySelectorAll("*[stroke-alignment]");
strokeEls.forEach((el,i) => {
let type = el.nodeName;
let style = window.getComputedStyle(el);
let strokeWidth = parseFloat(style.strokeWidth);
let strokeAlignment = el.getAttribute('stroke-alignment');
let offset = strokeAlignment==='outer' ? strokeWidth/2 : (strokeAlignment==='inner' ? strokeWidth / -2 : 0);
// convert primitive
if(type!=='path'){
el = convertPrimitiveToPath(el);
}
let d = el.getAttribute("d");
let polyPath = new paper.Path(el.getAttribute("d"));
let dOffset = offset ? PaperOffset.offset(polyPath, offset)
.exportSVG()
.getAttribute("d") : d;
el.setAttribute("d", dOffset);
});
body{
margin:2em;
}
svg{
width:100%;
overflow:visible;
border:1px solid #ccc;
}
<svg viewBox="0 0 12 6" xmlns="http://www.w3.org/2000/svg" stroke-width="0.5">
<path d="M1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" stroke="black" fill="none" stroke-linejoin="miter"/>
<path d="M1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" fill="none" stroke-linejoin="miter" stroke-alignment="outer" stroke="red" stroke-opacity="0.5" />
<path d="M7,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" stroke="black" fill="none" stroke-linejoin="round" />
<path d="M7,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3.5" fill="none" stroke-linejoin="round" stroke-alignment="inner" stroke="red" stroke-opacity="0.5" />
</svg>
<script src="https://unpkg.com/paper#0.12.15/dist/paper-full.min.js"></script>
<script src="https://unpkg.com/paperjs-offset#1.0.8/dist/paperjs-offset.js"></script>
However, the library struggles with complex shapes.

SVG with USE tag not rendering

The DOM already includes an empty SVG tag (svg). When I try to dynamically append a USE tag of an existing SVG symbol (symbol) with an id (iconId):
svg.empty();
svg[0].setAttribute('viewBox', symbol.getAttribute('viewBox'));
svg.append('<use xlink:href="#' + iconId + '"></use>');
it no longer renders the SVG. In Chrome, it renders if I add:
element.html(element.html());
or manually manipulate the viewBox attribute, but that's not a real solution and IE doesn't like it at all.
It's worth mentioning that if I append SVG graphics directly, the element renders.
What is happening here and why isn't the SVG drawing after appending the USE tag?
After all it was indeed a matter of namespaces.
Specifically, SVG elements and attributes must be created and set using document.createElementNS and node.setAttributeNS.
$(document).ready(function(evt) {
var svgns = 'http://www.w3.org/2000/svg',
xlinkns = 'http://www.w3.org/1999/xlink',
use = document.createElementNS(svgns, 'use');
use.setAttributeNS(xlinkns, 'xlink:href', '#save');
document.getElementById('useSVG').appendChild(use);
});
#svgStore {
display: none;
}
#useSVG {
width: 16px;
height: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<svg style="display:none;" id="svgStore" style="display: none;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<symbol viewBox="0 0 16 16" id="save"><title>save</title> <g id="svgstore3748a955346b4a088bbdc55a22f56504_x31_6_13_">
<path style="fill-rule:evenodd;clip-rule:evenodd;" d="M9,4h2V2H9V4z M13,13H3v1h10V13z M13,11H3v1h10V11z M13,0H0v16h16V3L13,0z
M3,1h9v4H3V1z M14,15H2V8h12V15z M13,9H3v1h10V9z">
</path>
</g>
</symbol>
</svg>
SVG use:
<svg id="useSVG" xmlns="http://www.w3.org/2000/svg"></svg>
Thanks to #RobertLongson and http://www.kevlindev.com/tutorials/basics/shapes/js_dom/ for directing to the answer.

Converting the DOM element in a String

I am working on svg. I made some shapes in svg using my javascript code. Now what i have to do is to get that code of svg which has been made as i draw some thing. i want to get that code in a form of string so for the sake of reuse or if can put that code in a .svg file it outputs the same what i made by myself using my javascript code.
Like My code made this
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="500" height="500" id="one">
<g id="container">
<rect id ="rect" x="0" y="0" width="0" height="0" fill="pink"
stroke="blue" stroke-width="2" />
</g>
Now what should i do to get all the code from to in a form of string and i can print that.
To get the equivalent of innerHTML in SVG you must first serialize the SVG, it is done like this:
​var svg = document.querySelector("svg");
var serializer = new XMLSerializer();
var string = serializer.serializeToString(svg);​
You can see an example here:
http://jsfiddle.net/rrPwS/
//in your javascript:
function getMyString() {
var theStringIWant = document.getElementById("container").innerHTML;
d.getElementbyId('theBox').value = theStringIWant
}
//and in your HTML:
<form>
<textarea id="theBox" rows="2" cols="60">Here's the string</textarea>
<input type="button" value="get the string" onclick="getMyString()" />
</form>

Chrome not rendering SVG referenced via <img> element

I am having issues with google chrome not rendering svg with an img element. This happens when refreshing the page and initial page load. I can get the image to show up by "Inspecting Element" then right clicking the svg file and opening the svg file in a new tab. The svg image will then be rendered on the original page.
<img src="../images/Aged-Brass.svg">
Totally at loss here as to what the issue is. The svg image renders fine in IE9 and FF just not in Chrome or Safari.
I have my MIME types set as well. (image/svg+xml)
EDIT:
Here is a simple html page that I built to help illustrate my issue.
<!DOCTYPE html>
<html>
<head>
<title>SVG Test</title>
<style>
#BackgroundImage{
background: url('../images/Aged-Brass.svg') no-repeat scroll left top;
width: 400px;
height: 600px;
}
#image_element {
width: 400px;
height: 600px;
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="image_element">
<img src="../images/Aged-Brass.svg">
</div>
<div id="BackgroundImage"></div>
</body>
</html>
As you can see I am trying to use an svg file in both an img element and in css as a background image. Neither work on the initial page load in chrome or safari. When I inspect element right click svg or click link to svg load in another window the svg file will render in original tab.
A simple and easy way; according to
https://css-tricks.com/forums/topic/svg-css-background-image-not-showing-in-chrome/
You have to open the .SVG file with a text editor (like notepad) and change
xlink:href="data:img/png;base64,
to:
xlink:href="data:image/png;base64,
it worked for me!
The svg-tag needs the namespace attribute xmlns:
<svg xmlns="http://www.w3.org/2000/svg"></svg>
i came here because i had the same problem,
when i inspect the element i can see the file, but on the site i can't (even when using localhost)
the answer to my problem was in saving the SVG file.
If you saved it from illustrator make sure to click 'embed' and not 'link'. as link will just refer to your local files rather than include the data (If i understand it correctly).
I read about it on the adobe website which has some other useful tips for exporting
http://www.adobe.com/inspire/2013/09/exporting-svg-illustrator.html
This worked for me, hope it was useful.
I came here because I had a similar problem, the image was not being rendered. What I found out was that the content type header of my testing server wasn't correct. I fixed it by adding the following to my .htaccess file:
AddType image/svg+xml svg svgz
AddEncoding gzip svgz
Use <object> instead (of course, replace each URL with your own):
.BackgroundImage {
background: url('https://upload.wikimedia.org/wikipedia/commons/b/bd/Test.svg') no-repeat scroll left top;
width: 400px;
height: 600px;
}
<!DOCTYPE html>
<html>
<head>
<title>SVG Test</title>
</head>
<body>
<div id="ObjectTag">
<object type="image/svg+xml" data="https://upload.wikimedia.org/wikipedia/commons/b/bd/Test.svg" width="400" height="600">
Your browser does not support SVG.
</object>
</div>
<div class="BackgroundImage"></div>
</body>
</html>
I had a similar problem and the existing answers to this either weren't applicable, or worked but we couldn't use them for other reasons. So I had to figure out what Chrome disliked about our SVGs.
In our case in turned out to be that the id attribute of the symbol tag in the SVG file had a : in it, which Chrome didn't like. Soon as I removed the : it worked fine.
Bad:
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 72 72">
<defs>
<symbol id="ThisIDHasAColon:AndChromeDoesNotLikeIt">
...
</symbol>
</defs>
<use
....
xlink:href="#ThisIDHasAColon:AndChromeDoesNotLikeIt"
/>
</svg>
Good:
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 72 72">
<defs>
<symbol id="NoMoreColon">
...
</symbol>
</defs>
<use
....
xlink:href="#NoMoreColon"
/>
</svg>
Adding the width attribute to the [svg] tag (by editing the svg source XML) worked for me:
eg:
<!-- This didn't render -->
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
...
</svg>
<!-- This did -->
<svg version="1.1" baseProfile="full" width="1000" xmlns="http://www.w3.org/2000/svg">
...
</svg>
I had this problem when i exported images from figma. Check source code of svg, if you have colon : in ids like this: id="paint1_linear_23:318" it'll make you the problems with rendering in chrome.
Just remove all colons in ids.
Don't forget make the same with referring to this ids like this: fill="url(#paint1_linear_23:318)".
.svg image does not have it's initial height and width. Therefore it is not visible. You have to set it.
You can do either in-line or in css file:
In-line:
<img src="../images/Aged-Brass.svg" class="image" alt="logo" style="width: 100px; height: 50px;">
Css file:
<img src="../images/Aged-Brass.svg" class="image" alt="logo">
.image {
width: 100px;
height: 50px;
}
Just replace <img> tag to <object> tag for SVG image.
<object data="assets/twitter-wrap.svg" type="image/svg+xml"></object>
I had the same problem. This problem was solved when I checked the file type that was accepted and set in headers "Content-Type", "image/svg+xml":
response.setHeader("Content-Type", "image/svg+xml");
I was able to use your sample to create a test page, and it worked just fine. My assumption is that there is something wrong with your svg file. Can you paste that here as well? Here is the sample I used.
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
<g>
<title>Layer 1</title>
<ellipse ry="30" rx="30" id="svg_1" cy="50" cx="50" stroke-width="5" stroke="#000000" fill="#FF0000"/>
</g>
</svg>
looks like a Chrome bug,
i did something else as i almost got crazy because of this...
using Chrom debugger if you change the css of the svg object it shows on the screen.
so what i did was:
1. check for screen size
2. listen to the "load" event of my SVG object
3. when the element is loaded i change its css using jQuery
4. it did the trick for me
if (jQuery(window).width() < 769) {
jQuery('object#mysvg-logo')[0].addEventListener('load', function() {
jQuery("object#mysvg-logo").css('width','181px');
}, true);
}
width: 180px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<object id="mysvg-logo" type="image/svg+xml" data="my svg logo url here">Your browser does not support SVG</object>
In my case this problem persisted when I created and saved the svg using Photoshop.
What helped, was opening the file using Illustrator and exporting the svg afterwards.
I also got the same issue with chrome, after adding DOCTYPE it works as expected
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
Before
<?xml version="1.0" encoding="iso-8859-1"?>
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="792px" height="792px" viewBox="0 0 792 792" style="enable-background:new 0 0 792 792;" xml:space="preserve">
<g fill="none" stroke="black" stroke-width="15">
......
......
.......
</g>
</svg>
After
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="792px" height="792px" viewBox="0 0 792 792" style="enable-background:new 0 0 792 792;" xml:space="preserve">
<g fill="none" stroke="black" stroke-width="15">
......
......
.......
</g>
</svg>
I exported my svg from Photoshop CC initially and had to manually add
version="1.1" into the <svg> tag
to get it showing on chrome.
Content type in the HTTP header from the server was the problem for me. I have a node.js server, added:
if( pageName.substring(pageName.lastIndexOf('.')) == '.svg' ) {
res.writeHead(200, { "Content-Type": "image/svg+xml" });
}
pageName is my local variable for what is requested.
My guess is this is a common problem! Am using the current version of Chrome (Mar 2020).
For me setting width / height to the img worked.
<asp:Image runat="server" ID="Icon" Style="max-width: 50px; max-height: 50px; position: relative;" />
I tried most of the solutions above, but didn't worked for me.
I used a svg sanitizr https://svg.enshrined.co.uk/ which worked.
I had a similar issue I think trying to set Sharepoint Icon to SVG and the file did not load properly (while Png did).
See thread: file-format-can-an-svg-file-be-used-as-a-site-icon-in-sharepoint-online
The reason for the issue is that the height and width flags are not set in the tag.
For instance, setting this works
I was able to fix the issue by:
Open SVG in a text editor (e.g. Notepad)
Include in the first SVG header code Width="80" Height="80" (perhaps can play with optimizing the size)
Save file and upload. IT WORKS!
So the first tag of my SVG looks like this
<svg height="80" width="80" id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 114.60458 114.60458">
Had the same problem. If server is configured correctly and .htacces is not the answer, might want to look the svg source you are embedding. Mine were created with text editor, rendered well on Chrome&Safari inside html5 code, once embedded, nothing was visible.
Added correct version, dimensions etc to the svg code and works like a charm.
Also, all styles inline.
Ie
<svg version="1.1" baseProfile="full" width="24" height="24" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" rx="2" ry="2" width="24" height="24" style="fill:#fbc800;width:24px;height:24px;" />
</svg>
Be careful that you don't have transition css property for you svg images
I don't now why, but if you make: "transition: all ease 0.3s" for svg image on Chrome the images do not appear
e.g:
* {
transition: all ease 0.3s
}
Chrome do not render svg.
Remove any transition css property and try again
On problems try to open the images first with a program that is capable to read svg-images.
If that fails, then the svg-image is somehow corrupted.
I had that case and copied the svg-paths in a new svg-image and adjusted all details of the svg-tags.
I never tested the reason that it was not rendering but suppose that some invisible special signs caused the render-error. Getting sometimes files edited on Mac I had this issue in other context already.
I was having the same issue with an SVG image included via the IMG tag. It turned out for me that Chrome didn't like there being a blank line directly at the top of the file.
I removed the blank line and my SVG immediately started rendering.
I make sure that I add the Style of the Image. It worked for me
style= "width:320; height:240"
Lighttpd
My problem was that was missing a mime handler for svg files in lighttpd configuration file. Adding these to your lighttpd.conf could solve your problem:
mimetype.assign = (
".pdf" => "application/pdf",
".sig" => "application/pgp-signature",
".spl" => "application/futuresplash",
".class" => "application/octet-stream",
".ps" => "application/postscript",
".torrent" => "application/x-bittorrent",
".dvi" => "application/x-dvi",
".gz" => "application/x-gzip",
".pac" => "application/x-ns-proxy-autoconfig",
".swf" => "application/x-shockwave-flash",
".tar.gz" => "application/x-tgz",
".tgz" => "application/x-tgz",
".tar" => "application/x-tar",
".zip" => "application/zip",
".mp3" => "audio/mpeg",
".m3u" => "audio/x-mpegurl",
".wma" => "audio/x-ms-wma",
".wax" => "audio/x-ms-wax",
".ogg" => "application/ogg",
".wav" => "audio/x-wav",
".gif" => "image/gif",
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".png" => "image/png",
".svg" => "image/svg+xml",
".xbm" => "image/x-xbitmap",
".xpm" => "image/x-xpixmap",
".xwd" => "image/x-xwindowdump",
".css" => "text/css",
".html" => "text/html",
".htm" => "text/html",
".js" => "text/javascript",
".asc" => "text/plain",
".c" => "text/plain",
".cpp" => "text/plain",
".log" => "text/plain",
".conf" => "text/plain",
".text" => "text/plain",
".txt" => "text/plain",
".spec" => "text/plain",
".dtd" => "text/xml",
".xml" => "text/xml",
".mpeg" => "video/mpeg",
".mpg" => "video/mpeg",
".mov" => "video/quicktime",
".qt" => "video/quicktime",
".avi" => "video/x-msvideo",
".asf" => "video/x-ms-asf",
".asx" => "video/x-ms-asf",
".wmv" => "video/x-ms-wmv",
".bz2" => "application/x-bzip",
".tbz" => "application/x-bzip-compressed-tar",
".tar.bz2" => "application/x-bzip-compressed-tar",
".odt" => "application/vnd.oasis.opendocument.text",
".ods" => "application/vnd.oasis.opendocument.spreadsheet",
".odp" => "application/vnd.oasis.opendocument.presentation",
".odg" => "application/vnd.oasis.opendocument.graphics",
".odc" => "application/vnd.oasis.opendocument.chart",
".odf" => "application/vnd.oasis.opendocument.formula",
".odi" => "application/vnd.oasis.opendocument.image",
".odm" => "application/vnd.oasis.opendocument.text-master",
".ott" => "application/vnd.oasis.opendocument.text-template",
".ots" => "application/vnd.oasis.opendocument.spreadsheet-template",
".otp" => "application/vnd.oasis.opendocument.presentation-template",
".otg" => "application/vnd.oasis.opendocument.graphics-template",
".otc" => "application/vnd.oasis.opendocument.chart-template",
".otf" => "application/vnd.oasis.opendocument.formula-template",
".oti" => "application/vnd.oasis.opendocument.image-template",
".oth" => "application/vnd.oasis.opendocument.text-web",
# make the default mime type application/octet-stream.
"" => "application/octet-stream",
)
References
Alternative of AddType in lighthttpd
In my case it was not loading svg due to image tag's id containing _ (underscore) in it so I removed that from
<image id="image0_1166:0000"> to <image id="image0"> and it worked. And don't forget to remove the same here
<use xlink:href="#image0">