hipsterdad hipsterdad - 1 month ago 12
HTML Question

video tag embedded in svg

I'm trying to embed a video inside an svg (the svg will only ever be viewed on the web). For that, I'm using the foreignObject tag:



<svg version="1.1" class="center-block" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="800" height="600" style="border: 1px solid black;">
<g>
<g transform="translate(151,104) scale(1,1)">
<rect x="0" y="0" width="300" height="200"></rect>
<foreignObject x="0" y="0" width="300" height="200">
<video width="300" height="200" controls="" style="position: fixed; left: 151px; top: 104px;">
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
</foreignObject>
</g>
</g>
</svg>





It "works" in the sense that the video is displayed, but it's off by several pixels relative to its parent . I tried several combinations: with style for the video, without styles, with namespaced video tag, etc. This works a lot better in firefox, but breaks completely in Chrome (Mac and Linux). I don't want to add an html tag outside the svg as this will be more hassle (the svg is created dynamically with React).

Has anyone been able to get something similar working? Thanks in advance.

Answer

There you go:

Translate moves the origin from the top left to the specified coordinates. If you embed an object at 0,0 it will be placed at the new origin. In this case you must embed it at -translation coordinates.

Even so, I had to increase the width and height. Why? I don't know. It doesn't seem to be a scale by 2. If someone knows I am curious to know.

<svg version="1.1" class="center-block" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="800" height="600"  style="border: 1px solid black;">
    <g>
        <g transform="translate(151,104) scale(1,1)">
            <rect x="0" y="0" width="300" height="200"></rect>
            <foreignObject x="-151" y="-104" width="500" height="400">
                <video width="300" height="200" controls="" style="position: fixed; left: 151px; top: 104px;">
                    <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
                </video>
            </foreignObject>
        </g>
    </g>
</svg>