canvasdrawImage缩放

我试图按比例缩放一个图像到canvas上。 我可以用固定的宽度和高度来缩放它,如下所示:

context.drawImage(imageObj, 0, 0, 100, 100) 

但是我只想调整宽度并调整高度。 像下面这样:

 context.drawImage(imageObj, 0, 0, 100, auto) 

我到处都可以想到,如果这是可能的,我还没有看到。

 context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height / imageObj.width) 

@TechMaze的解决scheme是相当不错的。

这里是一些正确性和引入image.onload事件后的代码。 image.onload太重要了,以避免任何forms的失真。

 function draw_canvas_image() { var canvas = document.getElementById("image-holder-canvas"); var context = canvas.getContext("2d"); var imageObj = document.getElementById("myImageToDisplayOnCanvas"); imageObj.onload = function() { var imgWidth = imageObj.naturalWidth; var screenWidth = canvas.width; var scaleX = 1; if (imgWidth > screenWidth) scaleX = screenWidth/imgWidth; var imgHeight = imageObj.naturalHeight; var screenHeight = canvas.height; var scaleY = 1; if (imgHeight > screenHeight) scaleY = screenHeight/imgHeight; var scale = scaleY; if(scaleX < scaleY) scale = scaleX; if(scale < 1){ imgHeight = imgHeight*scale; imgWidth = imgWidth*scale; } canvas.height = imgHeight; canvas.width = imgWidth; context.drawImage(imageObj, 0, 0, imageObj.naturalWidth, imageObj.naturalHeight, 0,0, imgWidth, imgHeight); } } 

如果您想按照屏幕尺寸正确缩放图片,可以这样做:如果您不使用JQUERY,请使用适当的等效选项replace$(window).width。

  var imgWidth = imageObj.naturalWidth; var screenWidth = $(window).width() - 20; var scaleX = 1; if (imageWdith > screenWdith) scaleX = screenWidth/imgWidth; var imgHeight = imageObj.naturalHeight; var screenHeight = $(window).height() - canvas.offsetTop-10; var scaleY = 1; if (imgHeight > screenHeight) scaleY = screenHeight/imgHeight; var scale = scaleY; if(scaleX < scaleY) scale = scaleX; if(scale < 1){ imgHeight = imgHeight*scale; imgWidth = imgWidth*scale; } canvas.height = imgHeight; canvas.width = imgWidth; ctx.drawImage(imageObj, 0, 0, imageObj.naturalWidth, imageObj.naturalHeight, 0,0, imgWidth, imgHeight);