Skip to content Skip to sidebar Skip to footer

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 w

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

Solution 2:

If I had this problem, I made this way:

<!DOCTYPE html><html><head><title>expExp.html</title><metahttp-equiv='Content-Type'content='text/html;charset=utf-8'/><script>var canvas;var ctx;
    functionfnOL()
    {
      canvas = document.getElementById("canvas");
   	  ctx = canvas.getContext("2d");
   	  fnOR();
    }
    functiondrawClock() {
      var radius;
   	  radius = canvas.height / 2;
      ctx.translate(radius, radius);
      radius = radius * 0.9;
      drawCircle(ctx, radius);
    }
    functiondrawCircle(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);
      }
    }
    functionfnOR()
    {
      canvas.width = window.innerWidth; /// equal to window dimension
      canvas.height = window.innerHeight;
      drawClock();
    }
    </script></head><bodyonload='fnOL();'onresize="fnOR();"><canvasid='canvas'>No Canvas</canvas><br/></body></html>

Post a Comment for "Html5 Canvas Responsiveness Does Not Work"