Showing posts with label SVG. Show all posts
Showing posts with label SVG. Show all posts

Friday, June 6, 2014

Folder-like html nested lists & Create your own CSS Icon Font

Recent trend saw the rise of mobile technology. In order to accommodate it, websites have to cater mobile users as well. Bootstrap, the most popular front-end framework for developing responsive, has take to web development to a more elegant way. At the same time, Icon Font has rode along the wave. Two major popular clans of Icon Font is Glyphicons & Font Awesome. Icon Font comes with a lots of benefits, eg, size, color, shape. Why it has such advantages? Reads more.

I involved in a website, where one of the requirement is to create Folder-like html nested lists. There's some trick to do it, some have introduced at:
1) using image (simple)

2) CSS background property (a bit imagination requires)

So far no issue, but to apply them on HTML with bootstrap, it really takes a bit extra of time, especially for those people that are not good in CSS, like me. I was looking fast-and-clean approach, something like CSS Icon Fonts, but built-in Glyphicons & Font Awesome does not come with it, Goggling other existing icon font also yields no result.

Then I bumped into this website, fontastic, prompting the idea of creating my Icon Font. From here, I found out that it needs .svg file to create icon font. SVG defines graphics in XML format. Now you know why Icon Font can be sized, since it's vector image. Thus I pick-up the tool, svg-edit, I used before in this post, and start creating the asset. Let's begin.

1) Download the "svg-edit", extract the zip file and click "svg-editor.html" to load the editor.
2) You'll be welcomed with default blank canvas. Click on the "Rectangle".


3) Try to create something like this. As you can see, I create the vertical rectangle over the size of the canvas. If i create with exact fit, it'd be far too small when Icon Font generated later, could be padding or margin issue. Try it yourself. And I found out that the color does not matter now.


4) When you done, save the file, let's say "m.svg". You can click on the "SVG", and reveal the svg content.



5) Now the asset is done. Let's go to create the Icon Font at fontastic.
6) Select "Modify Font" if it default to it, else create new font.



7) Give a descriptive name, this will be the name use in html.


8) Now we import the "m.svg" created early.


9) Import successful!


10) Preview of our Icon Font. It still looks weird, huh? Bear for while, click "Change set name".

 11) Change the set name



12) Click this set to add to your font, and you can see you have "1" ready to publish.


13) Click "Publish" tab and click the "Manual Download" button.


14) Now you can prepare to add it to your HTML. Let's use one of the very nice bootstrap menu library, metisMenu.

15) Download it's js library and sample. Add these few lines into the sample html provided by metisMenu.

  

This CSS is for adding extra second-level indentation.


Add this HTML to all the nested list "li" , and it is for adding the Icon Font generated.
  

16) Yeah, a nice folder-like html nested lists you got by now! You can download the source here.


p/s: When you use this Icon Font in Google Chrome browser, you might experience some weird issue. I think Google Chrome use some scaling technique to adjust the web content, so when you enlarge the browser to a special size like "110%", it skewed.


So, you have to apply the fix, for more please follow this link.
@media screen and (-webkit-min-device-pixel-ratio:0) {
 @font-face {
 font-family: 'startcoding';
 src: url("fonts/startcoding.svg#startcoding") format("svg");
 }
}

Monday, August 26, 2013

Web-based Javascript Interactive map makes easy with SVG

Recently I was thinking what else can i come up with, after seeing the successful story of the Waze, by using the world map. With the advancement of the html5, it can be done easily with canvas and SVG.

Of course, there's a lot of ready-made powerful tile-based detailed map API, eg.
1) Google Maps JavaScript API v3.
2) jquerygeo
3) leafletjs

However, the subtleness of them is beyond comparable with svg path-based map, with the aid of GPS and millions of dollars pumps by them.

Few of the prominent sites in Javascript svg path-based interactive map are:
1) jvectormap
2) amMap

So sad that my country of origin, Malaysia, is too small to be included by them. "Hey, why don't I create my own Interactive map", struck my mind.

Let's get started.
1) I need a map of my country. With the help of Google Image Search, there's plenty of them. Any image format will do, the important thing is the plain background. Beware of the infringement of the propriety though.

2) Once you find the proper image, you can using all sorts of image converting software to turn it into a .svg file. One option is Adobe Illustrator, if you are a designer. If you are just some independent programmer, online tool like Vector Magic, might be a good friend of you. Choose high-resolution when you do conversion.



3) Verify the newly generated .svg file if all the details are there. If not, you can use SVG-edit to add/remove the detail accordingly. Click on the particular svg-path and give a meaningful id to it. Click  twice will allow you to twist the svg-path, that something similar to spline.


4) Embed the svg element in the html page. This can be done easily.
*You might need to set/clip the width and height on the svg element, due to browser compatibility. See more here.

5) However, there's no element of interactive there. So we're gonna add it now. What we need are:

  • display the name of the region when mouse hovers
  • able to zoom
  • able to pan

6) To display the name of the region when mouse hovers, we use jquery and can be achieved easily through following code:

$(function() {
  $(".icon svg path").bind("mouseover", function( evt ) {
    var currentMap = evt.target.getAttributeNS(null,'id');
    if(currentMap != "background" 
        && currentMap != "KualaLumpur_border" 
        && currentMap != "Putrajaya_border"){
   //$(this).css('fill','blue');                            
   //$("#" + currentMap).removeAttr("fill");
   $("#" + currentMap).css('fill','blue');
   //evt.target from viewbox; text.text1 from diff cooor; need to offset
   // more complicated at: http://msdn.microsoft.com/en-us/library/ie/hh535760(v=vs.85).aspx
   var targetedPath = evt.target.getBBox();
   $(".icon svg text.text1").css('display','block')
                            .text(currentMap)
                            .attr( "x", targetedPath.x + targetedPath.width / 2)
                            .attr( "y", targetedPath.y + targetedPath.height / 2);
    }
  })
  .bind("mouseleave", function( evt ) {
    //IE9 & FF not supported
    //var currentMap = evt.target.getAttributeNS(null,'id');
    //console.log("mouseleave:" + currentMap);
  })
  .bind("mouseout", function( evt ) {
    var currentMap = evt.target.getAttributeNS(null,'id');
    if(currentMap != "background" &&
        currentMap != "KualaLumpur_border" &&
        currentMap != "Putrajaya_border"){
      //$(this).css('fill','c9c9c9');//IE9 & FF not supported
      //$("#" + currentMap).css('fill','c9c9c9');//IE9 & FF not supported
      var theCurrentMap = document.getElementById(currentMap);
      theCurrentMap.setAttribute('style', '');
      $(".icon svg text").css('display','none');
    }
  });
 });

*FireFox & IE9 does not fire 'mouseleave' event in the event bubling, so have to bind at 'mouseout' event. See more here.

7) What it does is loop through all the svg-paths, and bind the mouseover & mouseleave events. When mouse hovers, change the current element's css, then display the id of the region using a svg text on cursor's tip, with the help of  the current box selection, getBBox(), . What mouse leaves does is restoring whatever you've done on mouseover event. You might need to append this svg text programmatically though.


8) To enable the zooming capability, we use the following codes when DOM body's loads:
// Must be greater than 1. Increase this value for faster zooming (i.e., less granularity).
var zoomRate         = 1.1; 

function zoom(zoomType)
    {
  var theSvgElement = document.getElementById('svgElement');
  var viewBox = theSvgElement.getAttribute('viewBox'); // Grab the object representing the SVG element's viewBox attribute.
  var viewBoxValues = viewBox.split(' ');    // Create an array and insert each individual view box attribute value (assume they're seperated by a single whitespace character).

  viewBoxValues[2] = parseFloat(viewBoxValues[2]);  // Convert string "numeric" values to actual numeric values.
  viewBoxValues[3] = parseFloat(viewBoxValues[3]);
      
  if (zoomType == 'zoomIn')
  {
   viewBoxValues[2] /= zoomRate; // Decrease the width and height attributes of the viewBox attribute to zoom in.
   viewBoxValues[3] /= zoomRate; 
  }
  else if (zoomType == 'zoomOut')
  {
   viewBoxValues[2] *= zoomRate; // Increase the width and height attributes of the viewBox attribute to zoom out.
   viewBoxValues[3] *= zoomRate; 
  }
  else
   alert("function zoom(zoomType) given invalid zoomType parameter.");
      
  // Convert the viewBoxValues array into a string with a white space character between the given values.
  theSvgElement.setAttribute('viewBox', viewBoxValues.join(' '));
    }
        
    function zoomViaMouseWheel(mouseWheelEvent)
    {      
      //check for detail first so Opera uses that instead of wheelDelta 
      var delta=mouseWheelEvent.detail? mouseWheelEvent.detail*(-120) : mouseWheelEvent.wheelDelta 
      //if (mouseWheelEvent.wheelDelta > 0)
        zoom('zoomIn');
      else
        zoom('zoomOut');
        
      /* When the mouse is over the webpage, don't let the mouse wheel scroll the entire webpage: */
      mouseWheelEvent.cancelBubble = true; 
      return false;       
    }

 function initialize()
    {        
      /* Add event listeners: */
      // Don't let the mousewheel event bubble up to stop native browser window scrolling.
      //window.addEventListener('mousewheel', zoomViaMouseWheel, false);
      
      //FF doesn't recognize mousewheel as of FF3.x
      var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" 
 
      if (document.attachEvent) //if IE (and Opera depending on user setting)
        document.attachEvent("on"+mousewheelevt, zoomViaMouseWheel)
      else if (document.addEventListener) //WC3 browsers
        document.addEventListener(mousewheelevt, zoomViaMouseWheel, false)
    }

9) What it does is hooking-up the mousewheel event, and change the svg viewbox properties.
*Due to FireFox & Safari handles mousewheel event differently, we have to cater as well. See more here.

10) To enable panning, it needs a little more treatment.

// Number of pixels to pan per key press.  
var panRate          = 10;   

 var isDragging = false;
 var mouseCoords = { x: 0, y: 0 };

function hookEvent(element, eventName, callback)
    {
        if(typeof(element) == "string")
           element = document.getElementById(element);
        if(element == null)
           return;
        if(eventName == 'mousewheel')
        {
           element.addEventListener('DOMMouseScroll', callback, false); 
        }
        else
         {
           element.addEventListener(eventName, callback, false);
        }
    }
  
 function onMouseDown(e)
    {
        isDragging = true;
    }
        
    function onMouseUp(e)
    {
        isDragging = false;
    }
        
    function onMouseOver(e)
    {
        mouseCoords = {x: e.clientX, y: e.clientY};
    }
  
  function onMouseMove(e)
    {
        if(isDragging == true)
        {
           var xd = (e.clientX - mouseCoords.x);
           var yd = (e.clientY - mouseCoords.y);
           pan(xd, yd)
        }
            
        mouseCoords = {x: e.clientX, y: e.clientY};
            
        return cancelEvent(e);
   }
  
  function pan(x, y)
  {
   var theSvgElement = document.getElementById('svgElement');
   var viewBox = theSvgElement.getAttribute('viewBox'); // Grab the object representing the SVG element's viewBox attribute.
   var viewBoxValues = viewBox.split(' ');    // Create an array and insert each individual view box attribute value (assume they're seperated by a single whitespace character).

   viewBoxValues[0] = parseFloat(viewBoxValues[0]);  // Convert string "numeric" values to actual numeric values.
   viewBoxValues[1] = parseFloat(viewBoxValues[1]);
    
   viewBoxValues[0] -= x;//panRate; // Increase the x-coordinate value of the viewBox attribute to pan right.
   viewBoxValues[1] -= y;//panRate; // Increase the y-coordinate value of the viewBox attribute to pan down.
    
   theSvgElement.setAttribute('viewBox', viewBoxValues.join(' ')); // Convert the viewBoxValues array into a string with a white space character between the given values.
  }

 
  function cancelEvent(e)
     {
        e = e ? e : window.event;
        if(e.stopPropagation)
           e.stopPropagation();
        if(e.preventDefault)
           e.preventDefault();
        e.cancelBubble = true;
        e.cancel = true;
        e.returnValue = false;
        return false;
     }

function initialize()
    {        
        hookEvent('svgElement', 'mousedown', onMouseDown);
        hookEvent('svgElement', 'mouseup', onMouseUp);
        hookEvent('svgElement', 'mousemove', onMouseMove);
    }

11) What it does is quite similar to mousewheel event. The different is now it uses global variable to check the mouse-down and the distance of mouse move, and eventually apply that to svg viewbox properties.

12) That's it. Now a javascript  interactive map is created. Full codes here.