Search

12/23/2009

SVG vs. Canvas on Trivial Drawing Application

SVG vs. Canvas on Trivial Drawing Application, presentation

Conclusions for pixels
* For Canvas, pixels are native
* Emulating pixels with SVG results in a huge DOM
* Winner: Canvas

Conclusions for vectors
* For SVG, vector shapes and mouse interaction are native
* With Canvas, you need to implement everything by yourself (or use a library)
* Winner: SVG

Canvas to SVG
* Canvas provides the .toDataURL() -method for reading its image data - This data can be inserted into SVG image element

function importCanvas(sourceCanvas, targetSVG) {

// get base64 encoded png from Canvas
var image = sourceCanvas.toDataURL();

// Create new SVG Image element.
var svgimg = document.createElementNS(
"http://www.w3.org/2000/svg",
"image");
svgimg.setAttributeNS(
"http://www.w3.org/1999/xlink",
"xlink:href",
image);

// Append image to SVG
targetSVG.appendChild(svgimg);
}

SVG to Canvas
* There is no .toDataURL() -method for SVG
* Solution: Server-side rasterization from serialized SVG
* Server-side conversion with ImageMagick



// Save SVG from POST
$svg_xml = $_POST["svg_xml"];
file_put_contents("input.svg",$svg_xml);

// Run conversion program (ImageMagick)
system("convert input.svg output.png");

// Return the name of rasterization for client
echo "output.png"

?>


function importSVG(sourceSVG, targetCanvas) {

var svg_xml = (new XMLSerializer()).serializeToString(sourceSVG);

$.post("convert.php", { svg_xml: svg_xml },
function(data) {
var ctx = targetCanvas.getContext('2d');
var img = new Image();

img.onload = function() {
ctx.drawImage(img,0,0);
img.src = data;
}
});
}

Conclusion
* For pixel flare and other demo effects, go with Canvas
* But for user interaction and shape stacking, S to the V to the G!

cakejs, demo, CAKE Programming Tutrorials
CAKE is a JavaScript library that allows you to use the HTML5 canvas element as a scenegraph, much like an SVG or other vector image. This article will show you how to get started with this powerful library.

var circle1 = new Circle(100,
{
id: 'myCircle1',
x: CAKECanvas.width / 3,
y: CAKECanvas.height / 2,
stroke: 'cyan',
strokeWidth: 20,
endAngle: Math.PI*2
}
);
circle1.addFrameListener(
function(t, dt)
{
this.scale = Math.sin(t / 1000);
}
);

沒有留言: