动态地将画布宽度设置为与高度完全相等而不缩放变形

时间:2017-02-14 01:34:52

标签: html css canvas flexbox

以前,我运行此javascript来将画布元素的宽度调整为窗口高度:

let board = document.getElementById("board");
function resize() {
  // Our canvas must cover full height of screen
  // regardless of the resolution
  var height = window.innerHeight;

  // So we need to calculate the proper scaled width
  // that should work well with every resolution
  var ratio = board.width/board.height;
  var width = height * ratio;

  board.style.width = width+'px';
  board.style.height = height+'px';

  window.display.w = width;
  window.display.h = height;
}

window.addEventListener('load', resize, false);
window.addEventListener('resize', resize, false);

从那时起,我的设计要求已经发展到需要额外的画布。所以我已经添加了

<center>
<div class="container">
<canvas id="info" class="panel"></canvas>
<canvas id="board" class="panel"></canvas>
<canvas id="actions" class="panel"></canvas>
</div>

现在我的画布在高度伸展时扭曲了。我试图在画布代码中以编程方式绘制5行,只显示3行。

enter image description here

.container {
  display:flex;
  height:100vh;
  align-items:flex-start;
  flex-grow: 0;
}

.panel {
  display:flex;
}

#board {
  width:50%;
  height:100vh;
  background:#9b59b6;
}

#info {
  width:25%;
  height:100%;
  background:#3498db;
}

#actions {
  width:25%; 
  height:100%;
  background:#1abc9c;
}

如何使用flexbox为我的board画布元素指定宽度,使其不会拉伸绘图?

以前我的绘图有这种比例:

enter image description here

我也尝试将电路板的宽度设置为100vh,结果看起来并没有太大差异。

1 个答案:

答案 0 :(得分:2)

resize()回调函数中,还要确保设置画布位图的大小。目前仅设置元素大小。这可能需要对电路板的设计方式进行一些重组,但要消除您现在看到的问题。

function resize() {
  // Our canvas must cover full height of screen
  // regardless of the resolution
  var height = window.innerHeight;

  // So we need to calculate the proper scaled width
  // that should work well with every resolution
  var ratio = board.width/board.height;
  var width = height * ratio;

  board.width = width;      // make sure bitmap is updated as well
  board.height = height;

  board.style.width = width+'px';
  board.style.height = height+'px';

  window.display.w = width;
  window.display.h = height;
}

您也可以使用以下方法获取画布元素大小(CSS):

var rect = board.getBoundingClientRect();

然后相应地设置位图大小(注意影响元素大小的边框和填充):

board.width = rect.width;
board.height = rect.height;