Subpixel anti-aliased text on HTML5's canvas element

后端 未结 5 769
长发绾君心
长发绾君心 2020-12-02 14:31

I\'m a bit confused with the way the canvas element anti-aliases text and am hoping you all can help.

In the following screenshot the top \"Quick Brown Fox\" is an

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 15:02

    Matt, I sat with the (same/similar) problem last week, which, in my case, turned out to be because of differences in pixel densities on the devices I was testing; I wrote about it tonight - http://joubert.posterous.com/crisp-html-5-canvas-text-on-mobile-phones-and

    The link at posterous is dead, so here is the gist with the source code: https://gist.github.com/joubertnel/870190

    And the snippet itself:

      // Output to Canvas without consideration of device pixel ratio
      var naiveContext = $('#naive')[0].getContext('2d');    
      naiveContext.font = '16px Palatino';
      naiveContext.fillText('Rothko is classified as an abstract expressionist.', 10, 20);
    
      // Output to Canvas, taking into account devices such as iPhone 4 with Retina Display
      var hidefCanvas = $('#hidef')[0];
      var hidefContext = hidefCanvas.getContext('2d');
    
      if (window.devicePixelRatio) {
        var hidefCanvasWidth = $(hidefCanvas).attr('width');
        var hidefCanvasHeight = $(hidefCanvas).attr('height');
        var hidefCanvasCssWidth = hidefCanvasWidth;
        var hidefCanvasCssHeight = hidefCanvasHeight;
    
        $(hidefCanvas).attr('width', hidefCanvasWidth * window.devicePixelRatio);
        $(hidefCanvas).attr('height', hidefCanvasHeight * window.devicePixelRatio);
        $(hidefCanvas).css('width', hidefCanvasCssWidth);
        $(hidefCanvas).css('height', hidefCanvasCssHeight);
        hidefContext.scale(window.devicePixelRatio, window.devicePixelRatio);               
      }
    
      hidefContext.font = "16px Palantino";
      hidefContext.fillText("Rothko is classified as an abstract expressionist.", 10, 20);
    

提交回复
热议问题