css - html 在不拉伸(stretch) Canvas 的情况下在 div 中居中 Canvas

标签 css html canvas

<分区>

我有一个像这样的 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>

它使 Canvas 居中,但 Canvas 正在拉伸(stretch)。

我不希望 Canvas 被拉伸(stretch)。

我希望它居中而不拉伸(stretch)。如果 Canvas 是水平的,则水平居中,如果是垂直的,则依此类推。

最佳答案

删除 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

关于css - html 在不拉伸(stretch) Canvas 的情况下在 div 中居中 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39716195/

相关文章:

java - 如何将高清图像缩小为标清图像?

html - 如何从这个动画 SVG 中删除多余的空间(填充)?

c# - 使用 Html Agility Pack 的类在跨度后获取文本

css - 无法使用 Visual Studio Community 2017 打开 .css 文件

php - 试图在每个 <ul> 元素中只显示 4 个结果

php - 将值从选择表单传递到 mysql 数据库

javascript - 在鼠标悬停期间在 Canvas 中显示值

javascript - javascript中的重叠/ HitTest

javascript - fabric js - 生成图像中的对象与 Canvas 中的对象具有不同的定位

css - SVG - 多边形悬停无法正常工作