The movement is caused by the absence of hardware acceleration during repainting. When creating animations, it is crucial to select specific properties to animate in order to enhance performance. Opting to animate the transform
property is a more efficient choice compared to animating background-size
.
In order to transition from a smaller size to a larger size, I modified the jQuery animate()
function to a simple css()
alteration by adjusting the scale transformation. The value within the scale()
function indicates the new size. For instance, 2
represents 200% of the original size in this case.
$("#container").css({
"transform": "scale(2)"
});
The inclusion of the transition
property in the CSS enables control over the duration and easing of the change. By implementing this method in a div with overflow: hidden
, the desired background-image effect can be achieved.
$('body').on('click', '#container', function() {
// opting for transform over animating background-size
$("#container").css({
"transform": "scale(2)"
});
});
#container {
width: 500px;
height: 300px;
margin-top: 100px;
margin-left: 100px;
background-color: #eeeeee;
background-image: url("https://real-e-expo.com/img/609/m5d2c42466d2e9.jpg");
background-repeat: no-repeat;
background-position: center;
/* adjust transition speed here, with the second value representing duration */
transition: all 3s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>