Update 22 April, 2016: Nothing new, I just decided to check up on this, and post a quick code update. Firefox still performs as expected, IE doesn\'t perform at
Hooray! I'm not sure when the change came to be, but as of now, the Chrome bug mentioned in the comments above has been resolved, which seems to have resolved the issue.
My demo now works in all major browsers:
This is still an issue in Chrome version 76 (canary) and official ver. 74.
The workaround I used was to place the canvas before the svg
, not in the foreignObject
inside it and wrap the whole content with a div with position: relative
so the svg
can be positioned absolute
to be always above the canvas.
Also the wrapper div must have some additional css (flexbox in my case) so the canvas lays below the svg.
See it on CodePen
<div class="wrapper" style="width: 400px; height: 400px; display: flex; position: relative;">
<canvas></canvas>
<svg style="position: absolute" width="100%" height="100%">
<g transform="translate(200, 200)">
<circle cx="0" cy="0" r="30" fill="red"/>
<text x="-12" y="2" font-family="Arial" font-size="15px" fill="black">SVG</text>
</g>
</svg>
</div>
<script>
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;
ctx.fillStyle = "pink"
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText("Canvas", canvas.width / 2, 50);
</script>
The con of this approach is you won't access any canvas mouse/screen event listeners if the canvas is covered by the svg at 100%.