Tuesday, May 20, 2014

Android WebView: display SVG using HTML and Javascript

This example show how to display SVG in WebView, using HTML and Javascript.

Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. The SVG specification is an open standard developed by the World Wide Web Consortium (W3C) since 1999. ~ Wikipedia.

You can convert graph file from PNG to SVG using inkscape. Save your svg file in /assets, same level of our html, mypage.html

Modify /assets/mypage.html from the former exercise of WebView.

var p1;
var p2;
var canvas;
var context;
var cx;
var cy;
var x;
var y;
var canvasOffsetX;
var canvasOffsetY;

var imgSVG = new Image();
imgSVG.src = "test.svg";

function init(){
 p1 = document.getElementById('p1');
 p2 = document.getElementById('p2');
 canvas = document.getElementById('myCanvas');
 context = canvas.getContext('2d');
 canvasOffsetX = canvas.getBoundingClientRect().left;
 canvasOffsetY = canvas.getBoundingClientRect().top;
 canvas.width = window.innerWidth - (2 * canvasOffsetX);
 canvas.height = window.innerHeight - canvasOffsetY - 100;
 context.drawImage(imgSVG, 0, 0);

<BODY onload="init()" style="border:5px solid #000000;">

<p id='p1'>un-init</p>

<canvas id='myCanvas' style="border:1px solid #FF0000;">
Canvas not support!

<p id='p2'></p>


No comments: