Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I place a svg image/element on top a canvas element?

I am using WebGL to render an image and put it on a canvas. I am wondering is it possible to place an SVG element on top of that canvas?

I actually can move the vector image I draw on top of canvas manually. So I suppose there should be a way to do that.

like image 546
Kurt Liu Avatar asked Jun 04 '14 15:06

Kurt Liu


People also ask

How do I use canvas and SVG in HTML?

Canvas draws 2D graphics, on the fly (with a JavaScript). SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element. In SVG, each drawn shape is remembered as an object.

Can you put SVG on canvas?

To draw SVG onto canvas, you need to use SVG image. Firstly, use the <foreignObject> element which contains the HTML. After that, you need to draw the SVG image into the canvas.

When should I use canvas over SVG?

The<canvas> element is a container for graphics. SVG gives better performance with smaller number of objects or larger surface. Canvas gives better performance with smaller surface or larger number of objects. SVG is vector based and composed of shapes.

Can you put SVG inside I tag?

3. How to use inline SVG images. SVG images can be written directly into the HTML document using the <svg> </svg> tag.


1 Answers

Same as you place any two elements on top of each other? Give them both a parent with either position:relative; or position:absolute;. Set the second one (or both) to position:absolute; left: 0px; top:0px; z-index: 2;

<div style="position: relative;">
  <canvas id="c" width="300" height="300"></canvas>
  <img src="http://s.cdpn.io/3/kiwi.svg" 
       style="position: absolute; 
              left: 0px; 
              top:0px;
              z-index: 2;
              width: 300px;
       " />
</div>

Example:

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

function rand(r) {
   return Math.floor(Math.random() * r);
}

function draw() {
  ctx.fillStyle ="rgb(" + 
                rand(256) + "," +
                rand(256) + "," +
                rand(256) + ")";
  
  ctx.fillRect(
      -150 + rand(canvas.width), 
      -150 + rand(canvas.height),
      rand(300),
      rand(300));
   requestAnimationFrame(draw);
}
draw();
<div style="position: relative;">
      <canvas id="c" width="300" height="300"></canvas>
      <img src="http://s.cdpn.io/3/kiwi.svg" 
           style="position: absolute; 
                  left: 0px; 
                  top:0px;
                  z-index: 2;
                  width: 300px;
           " />
    </div>

This seems like it's already been answered but in the opposite way here

like image 138
gman Avatar answered Oct 01 '22 19:10

gman