SVG rendered into canvas blurred on retina display

后端 未结 1 1083

I have an issue with SVG rendered into canvas. On retina displays canvas rendered as base64 url and set as SRC into is blurred.

I\'ve tried various methods

1条回答
  •  攒了一身酷
    2020-12-06 14:49

    Retina display

    Retina and very high resolution displays have pixel sizes that are smaller than the average human eye can resolve. Rendering a single line then ends up looking a like a lighter line. To fix the issues involved pages that detect the high res display will change the default CSS pixel size to 2.

    The DOM knows this and adjusts its rendering to compensate. But the Canvas is not aware and its rendering is just scaled up. The default display rendering type for the canvas is bilinear interpolation. This smooths the transition from one pixel to the next which is great for photos, but not so great for lines, text, SVG and the like.

    Some solutions

    • First is to turn of bilinear filtering on the canvas. This can be done with the CSS rule image-rendering: pixelated; Though this will not create the quality of the SVG rendered on the DOM it will reduce the appearance of blurriness some users experience.

    • When rendering SVG to the canvas you should turn off image smoothing as that can reduce the quality of the svg image. SVG is rendered internally and does not need additional smoothing when the internal copy is rendered onto the canvas.

      To do this ctx.imageSmoothingEnabled = false;

    • Detect the CSS pixel size. The window variable devicePixelRatio returns the size of the CSS pixel compared to the actual screen physical pixel size. Retina and High res devices will typically have a value of 2. You can then use that to set the canvas resolution to match the physical pixel resolution.

      But there is a problem because devicePixelRatio is not supported on all browsers and devicePixelRatio is affected by the page zoom setting.

      So at the most basic using devicePixelRatio and the assumption that few people zoom past 200%.

    Code Assuming that the canvas.style.width and canvas.style.height are already correctly set.

    if(devicePixelRatio >= 2){        
        canvas.width *= 2;
        canvas.height *= 2;
    }
    

    Now that you have increased the resolution you must also increase the rendering size. This can be done via the canvas transform, and better yet create it as a function.

    function setCanvasForRetina(canvas){
        canvas.width *= 2;
        canvas.height *= 2;
        canvas.setTransform(2,0,0,2,0,0);
    }
    

    Note I do not increase the pixel size by the value of "devicePixelRatio" This is because retina devices will only have a resolution of 2 times, if the aspect ratio is greater than 2 it is because the client has zoomed in. To honor the expected behaviour of the canvas I do not adjust for zoom setting if I can. Though that is not a rule just a suggestion.

    A better Guess

    The two methods above are either a stop gap solution or a simple guess. You can improve your odds by examining some of the system.

    Retina displays currently come in a fixed set of resolutions for a fixed set of devices (phones, pads, notebooks).

    You can query the window.screen.width and window.screen.height to determine the absolute physical pixel resolution and match that against known retina displays resolutions. You can also query the userAgent to determine the device type and brand.

    Putting it all together you can improve the guess. The next function makes a guess if the display is retina. You can use something similar to determin if the device is retina and then increase the canvas resolution accordingly.

    Information for the following code found at wiki Retina Display Models This information can be machine queried using Wiki's SPARQL interface if you want to keep it up to date.

    Demo Guess if Retina.

    rWidth.textContent = screen.width
    rHeight.textContent = screen.height
    
    aWidth.textContent = screen.availWidth
    aHeight.textContent = screen.availHeight
    
    pWidth.textContent = innerWidth
    pHeight.textContent = innerHeight
    
    dWidth.textContent = document.body.clientWidth
    dHeight.textContent = document.body.clientHeight
    
    //doWidth.textContent = document.body.offsetWidth
    //doHeight.textContent = document.body.offsetHeight
    
    //sWidth.textContent = document.body.scrollWidth
    //sHeight.textContent = document.body.scrollHeight
    
    pAspect.textContent = devicePixelRatio
    
    userA.textContent = navigator.userAgent
    
    
    
    function isRetina(){
      // source https://en.wikipedia.org/wiki/Retina_Display#Models
      var knownRetinaResolutions = [[272,340], [312,390], [960,640], [1136,640 ], [1334,750 ], [1920,1080], [2048,1536], [2732,2048], [2304,1440], [2560,1600], [2880,1800], [4096,2304], [5120,2880]];
      var knownPhones =  [[960,640], [1136,640 ], [1334,750 ], [1920,1080]];
      var knownPads =  [[2048,1536], [2732,2048]];
      var knownBooks = [[2304,1440], [2560,1600], [2880,1800], [4096,2304], [5120,2880]];
    
      var hasRetinaRes = knownRetinaResolutions.some(known => known[0] === screen.width && known[1] === screen.height);
      var isACrapple = /(iPhone|iPad|iPod|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/.test(navigator.userAgent);
      var hasPhoneRes =  knownPhones.some(known => known[0] === screen.width && known[1] === screen.height);
      var isPhone = /iPhone/.test(navigator.userAgent);
      var hasPadRes =  knownPads.some(known => known[0] === screen.width && known[1] === screen.height);
      var isPad = /iPad/.test(navigator.userAgent);
      var hasBookRes =  knownBooks.some(known => known[0] === screen.width && known[1] === screen.height);
      var isBook = /Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh/.test(navigator.userAgent);
    
      var isAgentMatchingRes = (isBook && hasBookRes && !isPad && !isPhone) ||
          (isPad && hasPadRes && !isBook && !isPhone) ||
          (isPhone && hasPhoneRes && !isBook && !isPad)
      return devicePixelRatio >= 2 && 
             isACrapple && 
             hasRetinaRes && 
              isAgentMatchingRes;
    }
    
    guess.textContent = isRetina() ? "Yes" : "No";
        
    div, h1, span {
      font-family : arial;
    }
    span {
      font-weight : bold
    }

    System info

    Device resolution : by pixels
    Availabe resolution : by pixels
    Page resolution : by CSS pixels
    Document client res : by CSS pixels
    Pixel aspect :
    User agent :

    Best guess is retina "!"

    From your snippet

    This may do what you want. As I don't own any apple products I can not test it apart from forcing true on isRetina.

        function isRetina() {
            // source https://en.wikipedia.org/wiki/Retina_Display#Models
            var knownRetinaResolutions = [[272, 340], [312, 390], [960, 640], [1136, 640], [1334, 750], [1920, 1080], [2048, 1536], [2732, 2048], [2304, 1440], [2560, 1600], [2880, 1800], [4096, 2304], [5120, 2880]];
            var knownPhones = [[960, 640], [1136, 640], [1334, 750], [1920, 1080]];
            var knownPads = [[2048, 1536], [2732, 2048]];
            var knownBooks = [[2304, 1440], [2560, 1600], [2880, 1800], [4096, 2304], [5120, 2880]];
    
            var hasRetinaRes = knownRetinaResolutions.some(known => known[0] === screen.width && known[1] === screen.height);
            var isACrapple = /(iPhone|iPad|iPod|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/.test(navigator.userAgent);
            var hasPhoneRes = knownPhones.some(known => known[0] === screen.width && known[1] === screen.height);
            var isPhone = /iPhone/.test(navigator.userAgent);
            var hasPadRes = knownPads.some(known => known[0] === screen.width && known[1] === screen.height);
            var isPad = /iPad/.test(navigator.userAgent);
            var hasBookRes = knownBooks.some(known => known[0] === screen.width && known[1] === screen.height);
            var isBook = /Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh/.test(navigator.userAgent);
    
            var isAgentMatchingRes = (isBook && hasBookRes && !isPad && !isPhone) ||
                (isPad && hasPadRes && !isBook && !isPhone) ||
                (isPhone && hasPhoneRes && !isBook && !isPad);
          
          
            return devicePixelRatio >= 2 && isACrapple && hasRetinaRes && isAgentMatchingRes;
        }
        
        function svgToImage(svg){
            function svgAsImg() {
                var canvas, ctx;
                canvas = document.createElement("canvas");
                ctx = canvas.getContext("2d");
                var width = this.width;
                var height = this.height;
                var scale = 1;
                if(isRetina()){
                    width *= 2;
                    height *= 2;
                    scale = 2;
                }
    
                canvas.width = width;
                canvas.height = height;
                ctx.setTransform(scale, 0, 0, scale, 0, 0);
                ctx.imageSmoothingEnabled = false;  // SVG rendering is better with smoothing off
                ctx.drawImage(this,0,0);
                DOMURL.revokeObjectURL(url);
                try{
                    var image = new Image();
                    image.src = canvas.toDataURL();              
                    imageContainer.appendChild(image);
                    image.width = this.width;
                    image.height = this.height;
                }catch(e){  // in case of CORS error fallback to canvas
                    canvas.style.width = this.width + "px";  // in CSS pixels not physical pixels
                    canvas.style.height = this.height + "px";
                    imageContainer.appendChild(canvas);  // just use the canvas as it is an image as well
                }
            };
            var url;
            var img = new Image();
            var DOMURL = window.URL || window.webkitURL || window;
            img.src = url = DOMURL.createObjectURL(new Blob([svg], {type: 'image/svg+xml'}));           
            img.onload = svgAsImg;
        }
        
        svgToImage(svgContainer.innerHTML);
       

    Please Note.

    Most people who have 6/6 vision (20/20 for imperial countries) will be hard pressed to see the difference between the slightly blurry display of the canvas and the crisp DOM. You should ask yourself, did you need to have a closer look to make sure? can you see the blur at normal viewing distance?

    Also some people who have zoomed the display to 200% do so for good reason (vision impaired) and will not appreciate you circumventing their settings.

    0 讨论(0)
提交回复
热议问题