1

我正在尝试使用 HTML5 画布元素(如图所示)绘制一组圆圈。

当我调整浏览器大小时,上图会被裁剪。当我调整浏览器大小时,我希望它能够响应。

请帮助我使其响应。谢谢你。

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>

4

2 回答 2

2

初始化画布元素时会设置宽度和高度,因此您需要监听窗口调整大小事件并重置画布宽度和高度。

window.onresize = function() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
};
于 2016-07-29T17:30:56.553 回答
1

如果我有这个问题,我是这样做的:

<!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>

于 2016-07-29T17:09:23.560 回答