Можно ли сделать холст во flexbox с flex = 1 без дополнительного контейнера? - PullRequest
0 голосов
/ 09 января 2020

Я хочу отобразить холст с flex = 1 в flexbox, и я хочу, чтобы холст имел те же атрибуты ширины / высоты, что и его физический размер, поэтому я использую:

canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;

В тот момент, когда я это сделаю, холст будет не сжиматься, когда я делаю страницу меньше. Я пробовал это:

canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;

Но это не работает, как и любые другие вещи, которые я пробовал. У меня есть упаковка холст в дополнительный контейнер:

var f = footer.clientWidth;

function line() {
  var ctx = canvas.getContext('2d');
  ctx.strokeStyle = 'red';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(canvas.width, canvas.height);
  ctx.stroke();
}

narrower.onclick = function () {
  footer.style.width = (footer.clientWidth - 20) + 'px';
  canvas.width = canvas.clientWidth;
  canvas.height = canvas.clientHeight;
  line();
}

wider.onclick = function () {
  footer.style.width = (footer.clientWidth + 20) + 'px';
  canvas.width = canvas.clientWidth;
  canvas.height = canvas.clientHeight;
  line();
}
footer {
  height: 3em;
  display: flex;
  outline: 2px solid fuchsia;
}

#container {
  flex: 1;
  outline: 1px solid lime;
}

canvas {
  outline: 1px dashed cyan;
  width: 100%;
  height: 100%;
}
<footer id="footer">
  <button id="narrower">narrower</button>
  <div id="container">
    <canvas id="canvas">aaa</canvas>
  </div>
  <button id="wider">wider</button>
</footer>

Мой вопрос: можно ли это сделать без дополнительного контейнера?

1 Ответ

1 голос
/ 09 января 2020

Да, это то, что вы пытаетесь сделать:

var f = footer.clientWidth;

function line() {
  var ctx = container.getContext('2d');
  ctx.strokeStyle = 'red';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(container.width, container.height);
  ctx.stroke();
}

narrower.onclick = function() {
footer.style.width = (footer.clientWidth - 20) + 'px';
  container.width = container.clientWidth;
  container.height = container.clientHeight;
  line();
}

wider.onclick = function() {
  footer.style.width = (footer.clientWidth + 20) + 'px';
  container.width = container.clientWidth;
  container.height = container.clientHeight;
  line();
}
footer {
  height: 3em;
  display: flex;
  outline: 2px solid fuchsia;
}

#container {
  min-width: 0;
  display: block;
  flex: 1;
  outline: 1px solid lime;
  background: yellow
}
<footer id="footer">
  <button id="narrower">narrower</button>
  <canvas id="container">aaa</canvas>
  <button id="wider">wider</button>
</footer>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...