HTML5 canvas responsiveness does not work

狂风中的少年 提交于 2019-12-20 04:37:29

问题


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>

回答1:


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;
};



回答2:


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>


来源:https://stackoverflow.com/questions/38648922/html5-canvas-responsiveness-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!