2017-09-19 13 views

答えて

0

// Create a variable for the canvas and it's context 
 
var canvas = document.getElementById("imageCanvas"); 
 
var ctx = canvas.getContext("2d"); 
 

 
// Initialise an image object 
 
var image = new Image(); 
 

 
// When it loads an image 
 
image.onload = function() { 
 
    // Get the canvas' current style 
 
    var canvasStyle = getComputedStyle(canvas); 
 
    
 
    // Get it's current width, minus the px at the end 
 
    var canvasWidth = canvasStyle.width.replace("px", ""); 
 
    
 
    // Work out the images ratio 
 
    var imageRatio = this.width/this.height; 
 
    
 
    // Work out the new height of the canvas, keeping in ratio with the image 
 
    var canvasHeight = canvasWidth/imageRatio; 
 
    
 
    // Set the canvas' height in the style tag to be correct 
 
    canvas.style.height = canvasHeight+"px"; 
 
    
 
    // Set the width/height attributes to be correct (as this is what drawImage uses) 
 
    canvas.width = canvasWidth; 
 
    canvas.height = canvasHeight; 
 
    
 
    // Draw the image at the right width/height 
 
    ctx.drawImage(this, 0, 0, canvasWidth, canvasHeight); 
 
}; 
 

 
// Load an image 
 
image.src="https://placekitten.com/g/600/800";
#imageCanvas 
 
{ 
 
    width: 400px; 
 
    height: 400px; 
 
}
<canvas id="imageCanvas" width="400px" height="400px"></canvas>

、右の高さにキャンバスのサイズを変更し、右幅に画像を縮小します。うまくいけばコメントはすべてを説明します。

+0

コメントありがとう –

関連する問題