如何按比例缩小大宽度的画布,以使页面宽度不会变大

时间:2019-08-13 15:51:13

标签: javascript html css

我想在dom中附加一个大画布(宽度= 2000),并按比例缩小它以适合视口。但是,然后页面大小就变得不必要地大了。如何避免在缩小大画布的同时页面尺寸变大。

function addCanvas(element) {
  const canvas = document.createElement('canvas');
  
  canvas.width = 2000;
  canvas.height = 2000;
  
  canvas.style.transform = 'scale(0.2)';
  
  element.append(canvas);
}

addCanvas(document.getElementById('app'));
#app {
  width: 100%;
  height: 100%;
  background: #ccc;
}

#app canvas {
  transform-origin: 0px 0px;
  background: red;
}
<div id="app">
</div>

1 个答案:

答案 0 :(得分:0)

我不确定,但是我认为下面的代码正是您想要的,我刚刚添加了

 max-width: 100vw;
 max-height: 100vh;

并删除了缩放比例,并添加了常规重置。

function addCanvas(element) {
  const canvas = document.createElement('canvas');
  
  canvas.width = 2000;
  canvas.height = 2000;
  
  element.append(canvas);
}

addCanvas(document.getElementById('app'));
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#app {
  background: #ccc;
  /* Solution for additional Comment */
  overflow: hidden;
  max-width: 100vw;
  max-height: 100vh;
  display: flex;
  justify-content: center;
}

#app canvas {
  background: red;
  /* Solution */
  max-width: 100vw;
  max-height: 100vh;
}
<div id="app">
</div>