【问题标题】:html center a canvas inside a div without stretching the canvas [duplicate]html在div内居中画布而不拉伸画布[重复]
【发布时间】:2016-09-27 18:32:13
【问题描述】:

我有一个像这样的html:

.image-detail {
  height: 100%;
  width: 100%;
  display: block;
  position: relative;
}
canvas {
  display: block;
}
.image-detail-canvas {
  -moz-user-select: none;
  -webkit-user-select: none;
  max-width: 100% !important;
  max-height: 100% !important;
  position: absolute !important;
  left: 50% !important;
  top: 50% !important;
  transform: translate(-50%, -50%) !important;
}
<div class="image-detail">
  <canvas class="image-detail-canvas" id="image-canvas">

  </canvas>
</div>

它使画布居中,但画布正在拉伸。

我不希望画布被拉伸。

我希望它居中而不拉伸。如果画布水平居中,则水平居中,如果垂直居中,则依此类推。

【问题讨论】:

  • 你的问题是一个经常被问到的问题。如果您想在使用 CSS 调整大小时避免拉伸,那么通过设置宽度和高度中的一个但不是两者,让画布按比例调整大小。或者,设置画布元素的宽度和高度,不会拉伸像素。同样,这是 Stackoverflow 上的一个常见问题,因此请搜索 Stackoverflow 了解更多详细信息。

标签: css html canvas


【解决方案1】:

删除Position: absolute;translate

为您的canvas 添加一些宽度并添加margin: 0 auto;,希望对您有所帮助。

canvas {
  border: 1px solid;
  padding: 0;
  margin: auto;
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.image-detail-canvas {
  -moz-user-select: none;
  -webkit-user-select: none;
  max-width: 100% !important;
  max-height: 100% !important;
}
<div class="image-detail">
  <canvas class="image-detail-canvas" id="image-canvas" width="100" height="100">

  </canvas>
</div>

在这里查看:https://stackoverflow.com/a/7782251/5336321

【讨论】:

  • 这会拉伸画布...
  • @Kaiido 立即查看答案!
  • 我想将它水平和垂直居中。我猜它只是水平居中而不是垂直居中
  • @aryan 已在此回答stackoverflow.com/a/7782251/5336321
  • 我上面的代码也使cavas居中,但问题是它正在拉伸画布。我在这个画布中有图像,它正在拉伸......
【解决方案2】:

position 更改为absolute 就足够了,并为所有父元素添加宽度/高度定义(还有htmlbody):

html, body {
  width: 100%;
  height: 100%; 
  margin: 0;
}
.image-detail {
  height: 100%;
  width: 100%;
  display: block;
  position: relative;
}
canvas {
  border: 1px solid;
  display: block;
}
.image-detail-canvas {
  position: relative;
  max-width: 100%;
  max-height: 100%;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<div class="image-detail">
  <canvas class="image-detail-canvas" id="image-canvas" width="100" height="100">

  </canvas>
</div>

【讨论】:

    猜你喜欢
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2013-05-06
    • 2019-05-29
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多