【问题标题】:Canvas Zoom out Image Quality Loss画布缩小图像质量损失
【发布时间】:2014-02-11 20:06:12
【问题描述】:

我编写了一个用于缩放画布图像的代码,但如果尝试多次缩放图像,图像质量就会发生变化。 这是我使用 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");
    }
}

【问题讨论】:

    标签: html canvas html5-canvas


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果您使用canvas.drawImage(),则无法避免质量损失。

      只需更改 CSS widthheight 值即可进行缩放。这样就不会有质量损失了。

      编码也简单很多...

      【讨论】:

        猜你喜欢
        • 2012-06-22
        • 2016-09-28
        • 1970-01-01
        • 1970-01-01
        • 2014-03-22
        • 1970-01-01
        • 2012-10-08
        • 2019-12-13
        相关资源
        最近更新 更多