问题
I'm trying to resize rotated (transformed with css) object with vanilla js. Object origin is center and can't be changed.
I've found a function here which should do the thing, however still it doesn't looks ideal - left top corner change its position (half of pixels or so).
Here is a simplified codepen example.
What code modifications I need to do at getCorrection
to keep left top corner position always same?
UPDATE:
As per comments below, the calculation is accurate but browser just can't deal with fractions of a pixel perfectly which seems like a technical limitation? Any ideas how to fix?
回答1:
If you apply the transforms relative to the top left corner (transform-origin: top left
), then you don't need to calculate that correction factor. You can then wrap all the shapes if you need to position them on the page:
const obj = document.querySelector('.object');
const btn = document.querySelector('button');
let h = 100;
let w = 100;
btn.addEventListener('click', () => {
h += 5;
w += 5;
updateElement();
});
function updateElement() {
obj.style.width = w + 'px';
obj.style.height = h + 'px';
}
updateElement();
body {
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
overflow-y: scroll;
overflow-x: hidden;
}
button {
margin: 8px;
padding: 8px;
font-family: monospace;
border: 2px solid black;
background: transparent;
}
.container {
position: relative;
width: 100%;
height: 100%;
}
.object-initial {
position: absolute;
top: 16px;
left: 30%;
outline: 1px dashed black;
transform: rotate(20deg);
transform-origin: top left;
width: 100px;
height: 100px;
}
.object {
position: absolute;
top: 16px;
left: 30%;
outline: 1px solid black;
transform: rotate(20deg);
transform-origin: top left;
}
<button>Increase width and height</button>
<div class="container">
<div class="object"></div>
<div class="object-initial"></div>
</div>
来源:https://stackoverflow.com/questions/59427665/resize-rotated-object-without-left-top-corner-shift-sub-pixel-rendering-issue