14 June 2015

Integrating SVG and the Canvas Element in HTML




One option is to embed both the SVG and the canvas element directly into the HTML page, and then access the canvas element from script within SVG:

<!DOCTYPE html>
<head>
<title>Canvas and SVG</title>
<meta charset="utf-8" />
</head>
<body>
<canvas id="myCanvas" width="400px" height="100px" >
<p>canvas item alternative content</p>
</canvas>
<svg id="svgelem" height="400" >
<title>SVG Circle</title>
<script type="text/javascript" >
window. onload = function () {
document. getElementById("myCanvas" ). getContext('2d' );
context. fillStyle = 'rgba(0,200,0,0.7)' ;
context. fillRect(0, 0, 100, 100);
};
</script>
<circle id="redcircle" cx="100" cy="100" r="100" fill="red" stroke="#000" />
</svg>
</body>


Or you can embed the canvas element as a foreign object directly in the SVG:


<!DOCTYPE html>
<html>
<head>
<title>Accessing Inline SVG</title>
<meta charset="utf-8" >
</head>
<body>
<svg id="svgelem" height="400" width="600" >
<script type="text/javascript" >
window. onload = function () {
var context2 = document. getElementById("thisCanvas" ). getContext('2d' );
context2. fillStyle = "#ff0000" ;
context2. fillRect(0, 0, 200, 200);
};
</script>
<foreignObject width="300" height="150" >
<canvas width="300" height="150" id="thisCanvas" >
alternate content for browsers that do not support Canvas
</canvas>
</foreignObject>
<circle id="redcircle" cx="300" cy="100" r="100" fill="red" stroke="#000" />
</svg>
</body>
</html>



When the SVG element is embedded into the current web page, you can access HTML elements from within the SVG. However, you can also embed elements directly in SVG, using the SVG foreignObject element. This element allows us to embed XHTML, MathML, RDF, or any other XML-based syntax.

In both solutions, I was able to use getElementById(). However, if I want to manipulate the elements using other methods, such as getElementsByTagName(), I have to be care‐ful about which version of the method I use. For instance, I can use getElementsByTag Name() for the outer canvas element, but I would need to use the namespace version of the method, getElementsByTagNameNS, if the contained object is XML, such as RDF/ XML. Because the embedded object in the solution is HTML5, a namespace wasn’t necessary.

Once you have the canvas context, use the element like you would from script within HTML: add rectangles, draw paths, create arcs, and so on.

No comments:

Post a Comment