2016-09-21 3 views
5

イメージをキャンバス内に収まるように縮小していますが、私が苦労しているのはキャンバス要素の内側に中心を置くことですお願いします?任意のヘルプは、水平及び垂直の両方のために働くJS - センターイメージキャンバス要素内

https://jsfiddle.net/n7xL5c37/

var canvas = document.getElementById('canvas'); 
var image = new Image(); 
    image.src = 'http://placehold.it/300x550'; 
    image.onload = function() { 
     var canvasContext = canvas.getContext('2d'); 
     var wrh = image.width/image.height; 
     var newWidth = canvas.width; 
     var newHeight = newWidth/wrh; 
     if (newHeight > canvas.height) { 
        newHeight = canvas.height; 
      newWidth = newHeight * wrh; 
     } 

     canvasContext.drawImage(image,0,0, newWidth , newHeight); 
     }; 

答えて

4

var canvas = document.getElementById('canvas'); 
 
    var image = new Image(); 
 
    image.src = 'http://placehold.it/300x550'; 
 
    image.onload = function() { 
 
     var canvasContext = canvas.getContext('2d'); 
 
     var wrh = image.width/image.height; 
 
     var newWidth = canvas.width; 
 
     var newHeight = newWidth/wrh; 
 
     if (newHeight > canvas.height) { 
 
\t \t \t \t \t newHeight = canvas.height; 
 
     \t newWidth = newHeight * wrh; 
 
     \t } 
 
     var xOffset = newWidth < canvas.width ? ((canvas.width - newWidth)/2) : 0; 
 
     var yOffset = newHeight < canvas.height ? ((canvas.height - newHeight)/2) : 0; 
 

 
     \t canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight); 
 
     };
<canvas id="canvas" width="500" height="500" style="border: 1px solid black" />

+0

ブリリアント感謝をしたい場合は、このソリューションは正常に動作しますobject-fit: contain

に似た何かをしたいです! – Admamza

2

溶液を理解されるであろう。

まず分スケールはその後の計算にそのスケールを使用してIMGの幅と高さ

var w = img.width * scale; 
var h = img.height * scale; 

を取得するためにそのスケールを使用して、幅または高さ

var scale = Math.min(canvas.width/img.width, canvas.height/img.height); 

に合わせてあるスケールを見つけます中心からの距離の半分の左上にある

var left = canvas.width/2 - w/2; 
var top = canvas.height/2 - h/2; 
0

Passersbyのソリューションは、あなたはobject-fit: cover

const fitImageToCanvas = (image,canvas) => { 
    const canvasContext = canvas.getContext("2d"); 
    const ratio = image.width/image.height; 
    let newWidth = canvas.width; 
    let newHeight = newWidth/ratio; 
    if (newHeight < canvas.height) { 
    newHeight = canvas.height; 
    newWidth = newHeight * ratio; 
    } 
    const xOffset = newWidth > canvas.width ? (canvas.width - newWidth)/2 : 0; 
    const yOffset = 
    newHeight > canvas.height ? (canvas.height - newHeight)/2 : 0; 
    canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight); 
}; 
関連する問題