jquery画布图像大小覆盖

jquery canvas image size overlay

本文关键字:覆盖 图像 布图像 jquery      更新时间:2023-09-26

我有一个jQuery图像悬停,它将图像从灰度级更改为彩色。

工作正常,如果图像是100像素的话。

如果在CSS中,我想将图像缩放到其边界容器的100%,就像这个一样

.class { display: inline-block; width: 250px; height: 250px; }
.class img { display: inline-block; width: 100%; height: auto; }

因此,我有一个250px宽的div,该div中的图像被缩放到100%。

但如果图像是500像素宽,它会缩小它的比例。这很好,但当我将鼠标悬停在图像上,使其从黑白变为彩色时,彩色版本(我假设与画布重叠)显示的是500像素的图像,而不是250像素的图像。

在下面的jquery中,我如何告诉画布覆盖是包含div的100%?

$(".imglist a").hover(
    function() {
        var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        masky, maskwidth,
        image = new Image();
        image.src = this.getElementsByTagName('img')[0].src;
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.style.position = 'absolute';
        masky = image.height;
        maskwidth = Math.sqrt(image.width * image.width + image.height * image.height);
        ctx.rotate(0.45);
        $(this).find('div').prepend(canvas);
        (function animate() {
            if (masky <= -(image.width / 2)) {
                return false;
            } else {
                masky -= 15;
                ctx.save();
                ctx.rect(0, masky, maskwidth, image.height);
                ctx.clip();
                ctx.rotate(-0.45);
                ctx.drawImage(image, 0, 0);
                ctx.restore();
                window.requestAnimFrame(animate, 0);
            }
        })();
    }, 
    function() {
        $(this).find('canvas').animate({opacity: 0}, 500, function() {
            $(this).remove();
        });
    }
);
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function() {
    return window.requestAnimationFrame || 
    window.webkitRequestAnimationFrame || 
    window.mozRequestAnimationFrame || 
    window.oRequestAnimationFrame || 
    window.msRequestAnimationFrame || 
    function(callback, element) {
        window.setTimeout(callback, 1000 / 60);
    };
})();

尝试将width: 100%也添加到画布中:

canvas.style.width = '100%';

或者,使用jQuery:

$(canvas).css('width', '100%');