我是HTML5 Canvas的新手,我正在尝试在HTML5 Canvas中实现两个图像之间的交叉淡入淡出效果(使用GSAP)。我可以分别单独使用fadeIn和fadeOut,但是如果我尝试将这两种效果混合在一起,将无法正常工作。
如果运行我的代码片段并在两个div之间快速移动,您会发现图像突然改变。 (但是,如果您将鼠标悬停在1个div上而又不将其悬停在另一个div上,则它会逐渐消失)。
我希望结合使用FadeIn和fadeOut来实现带有GSAP Tweens的交叉淡入效果(就像https://stackoverflow.com/a/33560604/3565182一样)。
我们将不胜感激。
let backgroundCanvas = $('#background-canvas')[0];
let canvasContext = backgroundCanvas.getContext('2d');
/* setting height and width */
backgroundCanvas.height = 100;
backgroundCanvas.width = 150;
/* setting up images */
let image1 = new Image();
let image2 = new Image();
image1.src = "http://lorempixel.com/500/300?22";
image2.src = "http://lorempixel.com/500/300?44";
/* confirm image load */
image1.onload = () => $('body').append('Image 1 loaded -- ');
image2.onload = () => $('body').append('Image2 loaded -- ');
let currentImage;
let imageId;
let backgroundImageProps = {
opacity: 0
};
/* on hover */
$('.show-image').mouseenter(function() {
imageId = $(this).attr('id');
if (imageId == '1')
currentImage = image1;
else
currentImage = image2;
/* from opacity 0 to 1 */
TweenLite.to(backgroundImageProps, 2, {
opacity: 1,
ease: Power4.easeOut,
onUpdate: function() {
drawImage(currentImage)
}
});
});
/* on hover end */
$('.show-image').mouseleave(function() {
let imageToHide = currentImage;
/* from opacity 1 to 0 */
TweenLite.to(backgroundImageProps, 2, {
opacity: 0,
ease: Power4.easeOut,
onUpdate: function() {
drawImage(imageToHide)
}
});
});
/* canvas drawing logic */
function drawImage(imageToDealWith) {
let image = imageToDealWith;
canvasContext.save();
canvasContext.clearRect(0, 0, backgroundCanvas.width, backgroundCanvas.height, 0, 0);
canvasContext.globalAlpha = backgroundImageProps.opacity;
canvasContext.drawImage(image, 0, 0, image.width, image.height, 0, 0, backgroundCanvas.width, backgroundCanvas.height);
canvasContext.restore();
}
canvas {
display:block;
}
div {
display: inline-block;
border:1px solid black;
margin:10px;
padding:10px;
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenLite.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="background-canvas"></canvas>
<div class="show-image" id="1">Image 1 (Hover)</div>
<div class="show-image" id="2">Image 2 (Hover)</div>