Changing ìnnerHTML
property for svg elements might have been a problem in 2010.
2023 it works flawlessly in all modern browsers:
// OP's example
var r = Raphael("holder", 200, 300);
var t = r.text(50, 50, "ssdwqdwq").attr({
'font-size': 20,
'font-family': 'Arial',
'font-weight': 'bold',
fill: '#000',
width: 400
});
t.node.innerHTML='dddd';
/**
* add foreignObject
* to enable HTML elements
* make sure to apply the correct namespaces
* for <foreignObject> and inner <div>
*/
let nsSvg = 'http://www.w3.org/2000/svg'
let nsHtml = 'http://www.w3.org/1999/xhtml'
let foreignObject = document.createElementNS(nsSvg, 'foreignObject');
foreignObject.setAttribute('x', 20)
foreignObject.setAttribute('y', 50)
foreignObject.setAttribute('width', '100%')
foreignObject.setAttribute('height', 150)
let foreignObjectDiv = document.createElementNS(nsHtml, 'div');
foreignObjectDiv.innerHTML = `Foreign <em style="color:red">object</em> <strong>text</strong>`;
foreignObject.appendChild(foreignObjectDiv)
//append foreign object
r.canvas.appendChild(foreignObject)
svg{
border: 1px solid #ccc
}
text{
font-size:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.3.0/raphael.min.js"></script>
<div id="holder"></div>
Append HTML elements to SVG via <foreignObject>
It is crucial to use the correct namespaces when attaching the foreign object dynamically:
// foreignObject is a svg
let foreignObject = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
// HTML element within foreign object
let foreignObjectDiv = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
Keep in mind, foreignObject
will only work in applications with HTML rendering support.
A lot of graphic/desktop applications might omit its content.
You might also encounter issues trying to convert your svg to pdf in some libraries.
If you don't need complex multiline text layouts, you should better stick with SVG's native <text>
and <tspan>
elements.