可以使用CSS3的transition或者animation属性实现动画效果。通过JS控制属性的变化,实现将元素替换的动画效果。
代码示例: HTML代码:
CSS代码:
#container { position: relative; } #container img, #container canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; transition: opacity 1s ease-in-out; } #container canvas { opacity: 0; }
JS代码:
function replaceImage() { const container = document.getElementById('container'); const image = container.querySelector('img'); const canvas = container.querySelector('canvas'); const button = document.getElementById('replaceBtn');
// set canvas properties and draw image canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0);
// hide image and show canvas image.style.opacity = 0; canvas.style.opacity = 1;
// add button event listener to reverse animation button.removeEventListener('click', replaceImage); button.addEventListener('click', reverseAnimation); }
function reverseAnimation() { const container = document.getElementById('container'); const image = container.querySelector('img'); const canvas = container.querySelector('canvas'); const button = document.getElementById('replaceBtn');
// hide canvas and show image canvas.style.opacity = 0; image.style.opacity = 1;
// add button event listener to start animation again button.removeEventListener('click', reverseAnimation); button.addEventListener('click', replaceImage); }