Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve the Canvas image quality when client zooms in the page?

I know the HTML5 Canvas adopts Bitmap technology and has its own limitation on image quality when zooming in.

But is there any solution for keeping image quality if client zooms in the page by using zoom function of the browser (for example on chrome, customer use Ctrl + Mouse scroll)?

like image 535
Chiến Nghê Avatar asked Sep 06 '25 03:09

Chiến Nghê


1 Answers

You can force the browser to make your drawings higher resolution by using an over-sized canvas that is proportionally scaled down using CSS:

  1. Make the canvas element proportionally bigger than your intended viewport:

    canvas.width=600;
    canvas.height=300;
    
  2. Use CSS to proportionally (important!) scale the canvas down to the viewport size:

    canvas{ width:200px; height:100px; }
    
  3. Use context.scale to scale your drawings back up to the intended size:

    context.scale(3,3);
    

Then when the canvas is scaled using the accessibility features (f.ex ctrl+mouseScroll) your drawings will have enough pixel resolution to look acceptable when scaled up.

Here's a code demo using the W3schools link you site in your comments:

http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_canvas_tut_text2

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// scale all drawings back up to intended size
ctx.scale(3,3);
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);
/* PROPORTIONALLY resize the canvas to the intended viewing size */
canvas{width:200px; height:100px; border:1px solid red;}
<!-- make the canvas over-sized -->
<canvas id="myCanvas" width=600 height=300></canvas>
like image 113
markE Avatar answered Sep 07 '25 21:09

markE