Preserve original quality of image on canvas

对着背影说爱祢 提交于 2019-12-08 17:11:36

If you resize the image to 100x100 pixels, then you will have a 100x100 image. Do not change width and height of your image when you load it. Also there is no reason to use a image onload function and an imageFromURL function.

Said so, load your image, scale it to a width of 90px ( now you are doing 100 and scale of 0.9 so is 90px), place it on canvas.

The canvas is 400px, when you will export it you will specify a multiplier of 5 to get a 2000px canvas. The image will be stretched without loosing its original resolution. It will not improve over its standard resolution of course.

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;  
    var img = document.createElement('img');
    img.onload = function () {
      if (img.width < 1000 || img.height < 1000)
      {
        alert("upload image should be greater then 1000px*1000px");
        return;
      }
      var oImg = new fabric.Image(img);
      var oImg = oImg.set({left: 50, top: 100, angle: 00}).scaleToWidth(90);
      canvas.add(oImg);
      canvas.setActiveObject(oImg);
    };
    img.src = data;
  };
  reader.readAsDataURL(file);
});
document.querySelector('#txt').onclick = function (e) {
  e.preventDefault();
  canvas.deactivateAll();
  document.querySelector('#preview').src = canvas.toDataURL({multiplier: 5});
}
canvas{
  border: 1px solid black;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file">
<canvas id="canvas" width="400" height="400"></canvas>
<a href='' id='txt' target="_blank">Export me 5x Bigger ( 400x5=2000)</a>
<br />
<img id="preview" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!