图像仅占用盒子内的小空间

时间:2016-07-28 13:14:22

标签: javascript jquery html5 canvas fabricjs

我们正在使用stackoverflow links代码在网站上传图片

一旦我们上传,它只会占据here框中的一小部分。

但是图像应该占据整个盒子。

enter image description here

var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
  var file = e.target.files[0];
  var reader = new FileReader();
  reader.onload = function (f) {
    var data = f.target.result;                    
    fabric.Image.fromURL(data, function (img) {
      var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
      canvas.add(oImg).renderAll();
      var a = canvas.setActiveObject(oImg);
      var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
    });
  };
  reader.readAsDataURL(file);
});
canvas{
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="canvas" width="450" height="450"></canvas>

1 个答案:

答案 0 :(得分:3)

替换

var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);

var oImg = img.set({left: 0, top: 0, angle: 00, width: canvas.getWidth(), height: canvas.getHeight()});

这是限制图像尺寸的原因。此外,我不知道为什么你有这个规模 - 但如果你把它保持为.scale(0.9),它就不会填满整个方块。相反,它只会填充其宽度和高度的90%。

<强>段

&#13;
&#13;
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
  var file = e.target.files[0];
  var reader = new FileReader();
  reader.onload = function (f) {
    var data = f.target.result;                    
    fabric.Image.fromURL(data, function (img) {
      var oImg = img.set({left: 0, top: 0, angle: 00,width:canvas.getWidth(), height:canvas.getHeight()});
      canvas.add(oImg).renderAll();
      var a = canvas.setActiveObject(oImg);
      var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
    });
  };
  reader.readAsDataURL(file);
});
&#13;
canvas{
  border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="canvas" width="450" height="450"></canvas>
 Run code snippet
&#13;
&#13;
&#13;