Question

I want to make responsive canvas with its context. I have already made the canvas responsive; below you can see my resize function.

$(window).on('resize', function(event) {
    event.preventDefault();
    d.myScreenSize = {
        x: $('.mainCanvasWrapper').width(),
        y: $.ratio($('.mainCanvasWrapper').width())
    };
    console.log('d.myScreenSize ', d.myScreenSize);
    var url = canvas.toDataURL();
    var image = new Image();
    ctx.canvas.width = d.myScreenSize.x;
    ctx.canvas.height = d.myScreenSize.y;
    image.onload = function() {
        ctx.drawImage(image, 0, 0, $('#paper').width(), $('#paper').height());
        //the drawing is being blurry (blurred). Please, have a look at the screenshot i have posted. 
    }
    image.src = url;
    if (d.drawer == 'true') {
        socket.emit('windowResize', d.myScreenSize);
    };
});

enter image description here

I have tried many solutions and also I don't want to use any library can anyone suggest me better solution ?

Was it helpful?

Solution

You are scaling bitmap data which means you will have loss in quality when resizing it. If you went from a small size to a large size then the image will be blurry due to the interpolation that takes place.

What you would want to do is to store your drawings as vectors:

  • Keep the drawn points in arrays "internally"
  • When needed, redraw all the points to the canvas
  • When resized, scale the points accordingly, then redraw as above.

My suggestion when it comes to rescaling the points is to keep and use the original points as a basis every time as this will give you a more accurate scaling.

There are plenty of examples here on SO on how to store drawn points as well as redraw them. One that could be used for basis is for example: HTML canvas art, generate coordinates data from sketch.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top