0

I am trying to create a reponsive layout for the 3-d globe, I've stored it like this:

  <div class="text-center main">
      <canvas id='globe' width='100%' height='100%'></canvas>
  </div>

however, when I give fixed width and height of 700px it will display size I want on my screen. However, I want to make it responsive therefore when displayed on cell phones the globe does not break and instead gets smaller. Can someone explain why 100% is smaller than 500px and simply increasing percentage to 200 ~300 % fixes the problem?

Sujal Patel
  • 2,444
  • 1
  • 19
  • 38
haneulkim
  • 4,406
  • 9
  • 38
  • 80
  • Set the div size to 100% also, instead of just the canvas, as the canvas is the child element, it'll have boundaries set by its parent element – mattdaspy Jun 08 '19 at 05:34
  • I am setting both canvas and div to width and height of 100% and it will not show full globe. I can increase div height using px however I want to make it responsive. – haneulkim Jun 08 '19 at 05:53
  • have you tried 100vw and 100vh? – Duncan Leung Jun 08 '19 at 08:47

2 Answers2

1

(Codepen: http://jsfiddle.net/hmen49yj/ )

You CAN'T use percent in width and height attributes on canvas element.

you CAN'T use css as well, because it will scale the canvas. instead you should use javascript to set canvas size relative to it's container, at start and resize:

function resized(){
    var canvas = $('#globe');
    canvas.width(canvas.parent().width() );
    canvas.height(canvas.parent().height() );
}
resized();
$("body")[0].onresize = resized;
yaya
  • 7,675
  • 1
  • 39
  • 38
  • I've used second code and increased % to 700 and it seems to work fine. – haneulkim Jun 08 '19 at 05:50
  • @makewhite as i said, chrome will ignore % and consider it px. so your basically using 700px. not sure about other browsers. – yaya Jun 08 '19 at 05:52
  • oh but when I use percentage the full globe is not showing instead it is zoomed in very much. – haneulkim Jun 08 '19 at 05:55
  • @makewhite oops, it seems that css percentage will scale the canvas. you should use js to set canvas size as it described here: https://stackoverflow.com/a/18680851/4718434 – yaya Jun 08 '19 at 05:59
  • @makewhite something like this: http://jsfiddle.net/hmen49yj/ – yaya Jun 08 '19 at 06:25
  • @makewhite answer updated. – yaya Jun 08 '19 at 06:32
0

I recomend to you use this way ...

  <!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
    *{
        margin:0;
        padding:0
    }
    .main{
        position:absolute;
        width:100%;
        height:100vh;
        background: green;
    }
    #globe{
        position:relative;

        width:70%;
        height:20vh;
        background: red;
    }
    .text-center{
        text-align: center;
    }
</style>
</head>
<body>

<div class="text-center main">
    <canvas id='globe'></canvas>
</div>

</body>
</html>
Sabee
  • 1,763
  • 9
  • 19