简体   繁体   中英

HTML5 canvas responsiveness does not work

I am trying to plot a group of circles using an HTML5 canvas element ( as shown in this image ).

The above figure gets cropped when I resize the browser. I want it to be responsive when I resize the browser.

Please help me to make it responsive. Thank you.

 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); canvas.width = window.innerWidth; /// equal to window dimension canvas.height = window.innerHeight; var radius = canvas.height / 2; ctx.translate(radius, radius); radius = radius * 0.9; drawClock(); function drawClock() { drawCircle(ctx, radius); } function drawCircle(ctx, radius) { var ang; var num; for (num = 1; num <= 40; num++) { ang = num * Math.PI / 20; ctx.rotate(ang); ctx.translate(0, -radius * 0.85); ctx.rotate(-ang); ctx.beginPath(); ctx.arc(0, 0, radius / 20, 0, 2 * Math.PI); ctx.stroke(); ctx.rotate(ang); ctx.translate(0, radius * 0.85); ctx.rotate(-ang); } } 
 #canvas { display: block; } 
 <canvas id="canvas"></canvas> 

The width and height get set when you initialize your canvas element, so you need to listen to the window resize event and reset your canvas width and height.

window.onresize = function() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
};

If I had this problem, I made this way:

 <!DOCTYPE html> <html> <head> <title>expExp.html</title> <meta http-equiv='Content-Type' content='text/html;charset=utf-8'/> <script> var canvas;var ctx; function fnOL() { canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); fnOR(); } function drawClock() { var radius; radius = canvas.height / 2; ctx.translate(radius, radius); radius = radius * 0.9; drawCircle(ctx, radius); } function drawCircle(ctx, radius) { var ang; var num; for (num = 1; num <= 40; num++) { ang = num * Math.PI / 20; ctx.rotate(ang); ctx.translate(0, -radius * 0.85); ctx.rotate(-ang); ctx.beginPath(); ctx.arc(0, 0, radius / 20, 0, 2 * Math.PI); ctx.stroke(); ctx.rotate(ang); ctx.translate(0, radius * 0.85); ctx.rotate(-ang); } } function fnOR() { canvas.width = window.innerWidth; /// equal to window dimension canvas.height = window.innerHeight; drawClock(); } </script> </head> <body onload='fnOL();' onresize="fnOR();"> <canvas id='canvas'>No Canvas</canvas><br/> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM