How To fit images in canvas using HTML5 and JavaScript?

Hey,
I’ve been working on a project that allows a user to upload an image to canvas.
But as user upload an image, It goes out of the mobile screen and a horizontal scroll bar appears.
Please help me what code I need to put in to make the image responsive with canvas and also fit in all devices including mobile.

<canvas  width= "600px" height = "300px" id="canvas" ></canvas><br>
<input type="file" id="UploadFile" style="margin-left: 10px; "><br> 
<div id="preview"></div>

<script>
var $preview= $("#preview"); 
var canvas = $('#canvas')[0];
var context = canvas.getContext('2d');

$("#UploadFile").change(function (e) {
  var F = this.files[0];
  var reader = new FileReader();
  reader.onload = imageIsLoad;
  reader.readAsDataURL(F);  
});

function imageIsLoad(e) {
  var image = new Image();
  image.onload = function(){
    canvas.width  = this.width;    
    canvas.height = this.height;   
    context.drawImage(this, 0,0); 
	
  };
  image.src = e.target.result;
}

Hi,

I think this needs to go in the JS forum as you probably need to resize the canvas to the aspect ratio of the image.

Something like this I would guess :slight_smile:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Untitled Document</title>
<style>
#canvas {
	display:block;
	width:100%;
	max-width:800px;
	border:1px solid #000;
}
</style>
</head>

<body>
</body>
<canvas id="canvas" ></canvas>
<input type="file" id="UploadFile" style="margin-left: 10px; ">
<div id="preview"></div>


<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var $preview= $("#preview"); 
var canvas = $('#canvas')[0];
var context = canvas.getContext('2d');

$("#UploadFile").change(function (e) {
  var F = this.files[0];
  var reader = new FileReader();
  reader.onload = imageIsLoad;
  reader.readAsDataURL(F);  
});

function imageIsLoad(e) {
  var image = new Image();
  image.onload = function(){
    var ratio = this.height / this.width;
    canvas.height = canvas.width * ratio;   
    context.drawImage(this, 0,0, canvas.width, canvas.height); 	
  };
  image.src = e.target.result;
}
</script>
</body>
</html>

I’ll move to the js forum in case this is the wrong approach :slight_smile:

1 Like

Thanks for sharing…

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.