Search code examples
canvasgoogle-swiffy

How does google swiffy maintain vectors in Canvas tag


I've noticed that google swiffy conversions from flash somehow maintain text and vectors in a way that they are crisp on retina displays or if you zoom the browser, all vectors stay sharp.

For example. Load up this ad https://developers.google.com/swiffy/showcase/google-chrome-ad

Zoom your browser in on it as far as you can. You'll notice all the text and vectors are perfectly crisp. I'm trying to emulate this in my own hand coded canvas, but when I zoom in all my drawn shapes and text get blurry. They also look blurry on retina.


Solution

  • Different devices may have different pixelRatio. (See https://stackoverflow.com/a/8785677/512042 about pixelRatio)

    Also pixelRatio might change on pages zoom.

    Look at this article for more info: http://www.html5rocks.com/en/tutorials/canvas/hidpi/?redirect_from_locale=ru

    var width = 300;
    var heigth = 300;
    
    canvas.style.width = width + 'px';
    canvas.style.heigth = heigth + 'px';
    
    var ctx = canvas.getContext('2d');
    
    
    function draw() {
      var devicePixelRatio = window.devicePixelRatio || 1;
      var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                                ctx.mozBackingStorePixelRatio ||
                                ctx.msBackingStorePixelRatio ||
                                ctx.oBackingStorePixelRatio ||
                                ctx.backingStorePixelRatio || 1;
    
      var ratio = devicePixelRatio / backingStoreRatio;
    
      // change canvas "pixels" size
      canvas.width = 300 * ratio;
      canvas.height = 300 * ratio;  
      ctx.clearRect(0,0,300, 300);
    
    
      ctx.scale(ratio, ratio);
    
      ctx.arc(150, 150, 50, 0, 2 * Math.PI);
      ctx.fill();  
    }
    
    draw();
    
    // as there is no "on page zoom" event:
    setInterval(draw, 300);
    

    See DEMO. Try to zoom.