[英]Canvas drawImage scaling
我正在嘗試按比例縮放圖像到畫布。 我可以用固定的寬度和高度來縮放它,如下所示:
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的解決方案非常好。
這是在image.onload事件的一些正確性和介紹之后的代碼。 image.onload太重要了,以避免任何類型的失真。
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,用適當的等效選項替換$(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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.