我的代码会将本地图像打开到画布中。这是一个响应式页面,因此画布会根据窗口大小动态调整大小。我需要能够获得正在加载的图像的尺寸,获得画布的当前大小并按比例调整图像大小以适合画布。我试图用HTML5,CSS3,JQuery和Javascript写这些,但不知道该怎么做。这是我到目前为止的代码。
CSS
#main{ display:block; width:99%; border: 5px solid #0C0; }`
JAVASCRIPT
<script> //Loads the local file
$(function() {
$('#file-input').change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);});
function fileOnload(e) {
var $img = $('<img>', { src: e.target.result });
var canvas = $('#canvas')[0];
var context = canvas.getContext('2d');
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
</script>
<script type="text/javascript"> //Resizes the canvas
$(document).ready( function(){
//Get the canvas & context
var c = $('#canvas');
var ct = c.get(0).getContext('2d');
var container = $(c).parent();
//Run function when browser resize
$(window).resize( canvas );
function canvas(){
c.attr('width', $(container).width() ); //max width
c.attr('height', $(container).height() ); //max height
//Redraw & reposition content
var x = c.width();
var y = c.height();
ct.fillStyle = "#FFFFFF"; //white
ct.fillRect( 0, 0, x, y); //fill the canvas
}
//Initial call
canvas();
});
HTML
<input id="file-input" type="file" /> //Loads the image
<div id="main" role="main"> //The canvas
<canvas id="canvas"></canvas>
</div>