5

I have a html like:

.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>

It is centering the canvas but the canvas is stretching.

I dont want the canvas to be stretched.

I want it to be centered without stretching. If the canvas is horizontal center it horizontally and if vertical then so on.

chirag
  • 1,761
  • 1
  • 17
  • 33
varad
  • 7,309
  • 20
  • 60
  • 112
  • Yours is an often asked question. If you want to avoid stretching while resizing with CSS then let the canvas **resize proportionally** by setting either-but-not-both of width & height. Alternatively, set the canvas element width & height and no pixels will be stretched. Again, this is an often asked question on Stackoverflow so search Stackoverflow for more details. – markE Sep 27 '16 at 15:40

2 Answers2

5

Remove Position: absolute; and translate

Add some width to your canvas and put margin: 0 auto;, Hope that helps.

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>

Check here: https://stackoverflow.com/a/7782251/5336321

Community
  • 1
  • 1
Hitesh Misro
  • 3,397
  • 1
  • 21
  • 50
1

It should be sufficient to change position to absolute, plus add width/height definitions to all parent elements (also html and body):

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>
Johannes
  • 64,305
  • 18
  • 73
  • 130