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