将图像设置为背景时保留背景图像的纵横比

时间:2018-01-19 08:04:46

标签: wordpress canvas fabricjs aspect-ratio

当我使用宽高比在布料画布上设置背景图像时,我遇到了一个问题(原因是不在画布上拉伸图像)。图像宽高比工作正常,但是当我下载图像时,图像的高度和宽度是根据画布的宽度和高度,但我需要在上传时根据其实际宽度和高度下载图像。

$(function() {
  var canvas1 = new fabric.Canvas('canvas1');
  var imageSaver = document.getElementById('ftdownload');
  imageSaver.addEventListener('click', saveImage, false);
  
  function saveImage(e) {
    this.href = canvas.toDataURL({
      format: 'png',
      quality: 0.8
    });
    this.download = 'frontside.png';
  }

  var canvasWrapper = document.getElementById('canvas-wrapper');
  var canvasWrapperWidth = canvasWrapper.clientWidth;

  var canvas = document.getElementById('canvas');
  var canvasWidth = 0;
  var canvasHeight = 0;

  var imgWidth = 0;
  var imgHeight = 0;

  //Default
  var canvas = canvas1;
  canvas.backgroundColor = '#34AD39';
  canvas.renderAll();
  //Change background using Image
  document.getElementById('bg_image').addEventListener('change', function(e) {
    canvas.setBackgroundColor('', canvas.renderAll.bind(canvas));
    canvas.setBackgroundImage(0, canvas.renderAll.bind(canvas));
    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) {

        imgWidth = img.width;
        imgHeight = img.height;

        var aspectRatioConstant = imgHeight / imgWidth;

        // Set canvas width to its parent container width
        canvasWidth = canvasWrapperWidth;

        // Calculate canvas height
        canvasHeight = canvasWrapperWidth * aspectRatioConstant;
        canvas.setDimensions({
          width: canvasWidth,
          height: canvasHeight
        }, {
          cssOnly: false
        });
        $('.lower-canvas').attr('width', imgWidth);
        $('.lower-canvas').attr('height', imgHeight);
        $('.upper-canvas').attr('width', imgWidth);
        $('.upper-canvas').attr('height', imgHeight);

        canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));

      });
    };
    reader.readAsDataURL(file);
  });
});
#canvas-wrapper{
  width: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>

<div style="margin-top:20px;">
    <label class="control-label">Add Background Image</label>
    <input type="file" id="bg_image" />
</div>
<div id="canvas-wrapper">
  <canvas id="canvas1" style="border:1px solid #000"></canvas>
</div>
<a href="javascript:void(0);" title="Download Template" id='ftdownload' >
	Download
</a>

我正在开发woocommerce中的插件。有时候它的下载很好,有小尺寸的图像但是有超过5.2或5 Mb的图像,它会拉伸画布并下载错误文件。

0 个答案:

没有答案