Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html center a canvas inside a div without stretching the canvas [duplicate]

Tags:

html

css

canvas

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.

like image 347
varad Avatar asked Sep 27 '16 04:09

varad


People also ask

How do I center a canvas inside a div?

To center canvas in HTML 5, include the canvas tag in div tag. Then we can center align the div tag. By doing so, the canvas is also center aligned.

How do I center a canvas element in CSS?

Add text-align: center; to the parent tag of <canvas> . That's it.

How do I make my canvas fit the screen in HTML?

to set the canvas's width and height both to 100%. We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%.


2 Answers

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

like image 127
Hitesh Misro Avatar answered Nov 01 '22 15:11

Hitesh Misro


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>
like image 20
Johannes Avatar answered Nov 01 '22 17:11

Johannes