簡體   English   中英

drawImage將圖像調整為500px高

[英]drawImage resize image to 500px high

我試圖拍攝1280x960的圖像並使用drawImage調整大小,使其高600像素。 我已經計算出我認為我需要達到這個比例,但不知道如何應用......

 var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.onload = function () { canvas.height = this.height; canvas.width = this.width; ratio = canvas.height / canvas.width; console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio); ctx.drawImage(img, 0, 0, 300, 500); } img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg'; 
 <canvas id="mycanvas"></canvas> 

如何指定生成的圖像大小,使寬度自動? 我最終希望此功能將任何圖像的大小調整為500像素高。

我將比率應用於你對drawImage的調用,它似乎有效:

ctx.drawImage(img, 0, 0, 500 / ratio, 500);

 var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.onload = function () { canvas.height = this.height; canvas.width = this.width; ratio = canvas.height / canvas.width; console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio); ctx.drawImage(img, 0, 0); canvas.style.width = 500 / ratio + "px"; canvas.style.height = 500 + "px"; } img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg'; 
 <canvas id="mycanvas"></canvas> 

這是一個解決方案,有點迂回,但似乎工作。 我使用原始大小的畫布中的toDataURL()創建了一個新圖像。 盡管新圖像被縮小,但是總尺寸仍然是原始圖像的尺寸,使得剩余空間是透明的。 然后我將此圖像設置並剪輯到新畫布中。 生成的畫布具有正確大小的圖像,可以使用所需尺寸進行復制和粘貼。

如果下面的代碼段沒有在新畫布中顯示圖像,請嘗試以下小提琴,這似乎運作良好: https//jsfiddle.net/jfeferman/u80fhy0z/

 var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.crossOrigin = "Anonymous"; img.onload = function () { canvas.height = this.height; canvas.width = this.width; ratio = canvas.height / canvas.width; console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio); ctx.drawImage(img, 0, 0, 500 / ratio, 500); var newImage = new Image(); newImage.crossOrigin = "Anonymous"; newImage.src = canvas.toDataURL(); var newCanvas = document.getElementById("newcanvas"); newCanvas.height = 500; newCanvas.width = 500 / ratio; var newCtx = newCanvas.getContext('2d'); newCtx.drawImage(newImage, 0, 0, 500 / ratio, 500, 0, 0, 500 / ratio, 500); } img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg'; 
 #mycanvas { display: none; } 
 <canvas id="newcanvas"></canvas> <canvas id="mycanvas"></canvas> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM