Search code examples
javascripthtmlhtml5-canvasretina-display

HTML Canvas at varying pixel densities


I'm hoping someone out there can help with this as I can't seem to find a solid solution.

Is there a framework or general setup to get HTML canvas rendering nicely, and at the correct size at varying pixel densities?

I understand why the issue exists. I've searched pretty thoroughly so apologies if this has been asked many times before but I still haven't seen a robust solution.

ADDITION: To clarify, canvas renderings look fuzzy on a retina screen, I was thinking there would be a way to get the renderings looking sharp no matter where they are being viewed. The fabric framework looks amazing but their demos still look fuzzy on my retina screen.


Solution

  • If you look at, for example three.js source, it implements resizing like this:

    this.setSize = function ( width, height, updateStyle ) {
    
            _width = width;
            _height = height;
    
            _canvas.width = width * pixelRatio;
            _canvas.height = height * pixelRatio;
    
            if ( updateStyle !== false ) {
    
                _canvas.style.width = width + 'px';
                _canvas.style.height = height + 'px';
    
            }
    
            this.setViewport( 0, 0, width, height );
    
        };
    
    this.setViewport = function ( x, y, width, height ) {
    
            _viewportX = x * pixelRatio;
            _viewportY = y * pixelRatio;
    
            _viewportWidth = width * pixelRatio;
            _viewportHeight = height * pixelRatio;
    
            _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
    
        };
    

    Where _gl seems to be the canvas context.

    It seems like they are just taking a width and height (as in screen width and height for example) and multiplying it with a pixel ratio, which is some integer between like 1-4 as far as I know.