尝试在画布图像上创建缩放插件

时间:2016-04-15 10:51:33

标签: jquery html css canvas

我正在尝试在画布图像上创建缩放插件[我知道有预定义的插件可用,想到自己做这个]。在鼠标悬停在画布图像上时,我将原始图像的特定部分复制到放置在原始图像下方的另一个画布上。我试过ctxZoom.scale(2, 2);,但复制的图像没有变焦。在将鼠标移动到真实图像上时,缩放图像应显示在原始图像下方,而现在不会发生。我知道哪里出错了?

JsFiddle Link

HTML

<div id="imageContainer">
    <div class="active">
        <canvas id="canvas"></canvas>
        <canvas id="canvasZoom"></canvas>
    </div>
</div>

JS

$(document).ready(function() {
    var canvasZoom = document.getElementById('canvasZoom');
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();

    loadImage = function(src) {

        img.crossOrigin = '';
        img.src = src;

        img.onload = function() {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.restore();
            ctx.drawImage(img, 0, 0, img.width, img.height);
        }
    }
    loadImage("http://www.foreignstudents.com/sites/default/files/webfm/car_0.jpg");

    function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
            x: evt.clientX - rect.left,
            y: evt.clientY - rect.top
        };
    }
    canvas.addEventListener('mousemove', function(e) {
        $("#canvasZoom").show();
        $('#canvasZoomm').css({
            left: e.pageX - 150,
            top: e.pageY
        });
        var mousePos = getMousePos(canvas, e);
        console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y)
        //grab the context from your destination canvas
        var ctxZoom = canvasZoom.getContext('2d');
        ctxZoom.scale(2, 2);//Not Working
        ctxZoom.putImageData(ctx.getImageData(mousePos.x - 150, mousePos.y - 60, 500, 500), 0, 0);
         ctxZoom.scale(2, 2);//Not Working
        ctx.restore();

    });
    canvas.addEventListener('mouseout', function(e) {
        //$("#canvasZoom").hide('slow');
    });

});

1 个答案:

答案 0 :(得分:1)

putImageData() will bypass any transformations applied to the canvas' context. And there is really no need to use transformations in the first place as you can simply draw the image at double size (and as well avoiding cors issues):

ctxZoom.drawImage(img, mousePos.x - 150, mousePos.y - 60, 500, 500, 
                  0, 0, img.width*2, img.height*2);

Example modification

Of course, you need to to set the source and destination rectangles as you want them, as well as checking for boundaries. You can see this answer as well as this (limit bounds) for more details.