1

我编写了一个用于缩放画布图像的代码,但如果尝试多次缩放图像,图像质量就会发生变化。这是我使用 canvas2image 插件的代码,我正在将画布转换为普通图像。

任何人都可以建议我做错什么吗?

function imgZoom(operation) {
    var zoomImageObj = document.getElementById("originalImage");
    var zoomedCanvas = $("#zoomCanvasPreview")[0];
    var zoomedContext = zoomedCanvas.getContext("2d");

    var selectedImgWidth = $('#originalImage').width();
    var selectedImgHeight = $('#originalImage').height();

    $("#zoomCanvasPreview").attr("height", selectedImgHeight);
    $("#zoomCanvasPreview").attr("width", selectedImgWidth);

    var previewHeight = $("#zoomCanvasPreview").height();
    var previewWidth = $("#zoomCanvasPreview").width();

    var zoomFactor = $("#zoomFactor option:selected").val();

    // Making the zoomfactor string as float point then parsing for addition

    // zoomFactor values if user selected 5%(0.05), 10%(0.1), 15(0.15) &etc
    var zoomPercent = 1 + parseFloat(zoomFactor);

    if(operation == 'zoomIn') {
        newZoomWidth = Math.round(previewWidth *  zoomPercent) ;
        newZoomHeight = Math.round(previewHeight *  zoomPercent) ;
    } else if(operation == 'zoomOut'){
        newZoomWidth = Math.round( previewWidth / zoomPercent );
        newZoomHeight = Math.round( previewHeight / zoomPercent );
    }

    if( (newZoomWidth >= 0) && (newZoomHeight >= 0) )
    {
        $("#zoomCanvasPreview").attr("width", newZoomWidth);    
        $("#zoomCanvasPreview").attr("height", newZoomHeight);

        // Drawing the image to canvas
        zoomedContext.drawImage(zoomImageObj, 0, 0, imgWidth, imgHeight, 0, 0, newZoomWidth, newZoomHeight );

        //return canvas.toDataURL("image/png");
        var zoomedCanvas = $("#zoomCanvasPreview")[0];

        oImgConvertExt = Canvas2Image.saveAsPNG(zoomedCanvas, true);
        $("#originalImage").attr("src", oImgConvertExt.src);
        $("#originalImage").attr("style", "display: none; visibility: hidden; width: "+newZoomWidth+"px; height: "+newZoomHeight+"px;");
    } else {
        alert("Reached maximum zoom out limit");
    }
}
4

2 回答 2

0

图像质量不会改变如果您使用 .SVG 格式的图像,即使您放大或缩小这些图像也不会失真

于 2013-06-07T09:17:18.977 回答
0

如果您使用canvas.drawImage().

只需通过更改 CSSwidthheight值进行缩放。这样就不会有任何质量损失。

编码也简单多了...

于 2014-02-11T12:06:12.910 回答