简体   繁体   中英

jquery canvas image size overlay

I have a jQuery image hover that changes an image from greyscale to colour.

Works fine, if the image is say, 100px fine.

Bit if in CSS i want to scale the image to 100% of its bounding container like this

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

So i have a div that is 250px wide, and the image inside that div is scaled to 100%.

But if the image is say, 500px wide, it's scaling it down. which, works fine, but when I hover over the image for it to change from black and white to color, the color version (overlapped by canvas i assume) is showing the 500px image, not the 250px version.

How in the jquery below do i tell the canvas overlay to be 100% of the containing div?

$(".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);
    };
})();

Try adding width: 100% to your canvas as well:

canvas.style.width = '100%';

Or, using jQuery:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM