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.
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.
Add text-align: center; to the parent tag of <canvas> . That's it.
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%.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With