# Bildbearbeitung HTML5 Canvas Fabric.js Jquery



## lukme (13. Apr 2015)

Hallo liebes Forum, ich bin relativ neu im Bereich JS.
Mein momentanes Projekt ist eine Art Frontend-Bildbearbeitung. Der User lädt ein Bild hoch, welches er dann mit vorgegebenen Filtern bearbeiten kann. Einige der Filter sollen bereits von anfang an über das Bild gelegt werden.
Ich bin mir leider nicht sicher, wie man dies umsetzen kann. Ich setzte es mit einem HTML5 Canvas Element mit jquery und fabric.js um.
Kann mir jemand helfen/einen Denkanstoß geben, wie ich die Filter nach dem Upload direkt ohne Userinteraktion anwende?

```
<meta charset="utf-8"/>
<input type="file" id="imageLoader" name="imageLoader" />
<canvas id="canvas" height="500" width="500"></canvas>
<h3>Filters:</h3>
  <p>
//Filter von der Checkbox "Start" sollen direkt nach Userupload angewendet werden
    <label><span>Start:</span> <input type="checkbox" id="start" ></label>
  </p>
<label>Threshold: <input id="remove-white-threshold" value="150" min="100" max="255" type="range"></label>
    <br>
</p>
<p>
    <label><span>Invert:</span> <input id="invert" type="checkbox"></label>
  </p>
<a id="imageSaver" href="#">Save image</a><br>
<button id="button">SVG</button>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
```


```
<script>
$(document).ready(function() {
 
 
    (function() {
   
  fabric.Object.prototype.transparentCorners = false;
  var $ = function(id){return document.getElementById(id)};
 
  function applyFilter(index, filter) {
    var obj = canvas.getActiveObject();
    obj.filters[index] = filter;
    obj.applyFilters(canvas.renderAll.bind(canvas));
  }
 
  function applyFilterValue(index, prop, value) {
    var obj = canvas.getActiveObject();
    if (obj.filters[index]) {
      obj.filters[index][prop] = value;
      obj.applyFilters(canvas.renderAll.bind(canvas));
    }
  }
 
  fabric.Object.prototype.padding = 5;
  fabric.Object.prototype.transparentCorners = false;
 
var canvas = this.__canvas = new fabric.Canvas('canvas'),
f = fabric.Image.filters;
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
 
 
 
function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) {
        var img = new Image();
        img.onload = function () {
            var imgInstance = new fabric.Image(img, {
                scaleX: 0.7,
                scaleY: 0.7
               
            })
       
            canvas.add(imgInstance);
        }
        img.src = event.target.result;
    }
   
    reader.readAsDataURL(e.target.files[0]);
}
 
                             
  canvas.on({
    'object:selected': function() {
      fabric.util.toArray(document.getElementsByTagName('input'))
                          .forEach(function(el){ el.disabled = false; })
 
      var filters = ['grayscale', 'invert', 'remove-white', 'sepia', 'sepia2',
                      'brightness', 'noise', 'gradient-transparency', 'pixelate',
                      'blur', 'sharpen', 'emboss', 'tint', 'multiply', 'blend'];
 
      for (var i = 0; i < filters.length; i++) {
        $(filters[i]).checked = !!canvas.getActiveObject().filters[i];
      }
    },
    'selection:cleared': function() {
      fabric.util.toArray(document.getElementsByTagName('input'))
                          .forEach(function(el){ el.disabled = true; })
    }
  });
$('button').onclick = function() {
     console.log(canvas.toSVG());
};
//Grayscale+RemoveWhite+Tint Filter
$('start').onclick = function(){
    applyFilter(0, this.checked && new f.Grayscale());
    applyFilter(2, this.checked && new f.RemoveWhite({
      threshold: $('remove-white-threshold').value,
      distance: '1',
    }));
    applyFilter(12, this.checked && new f.Tint({
      color: '#000',
      opacity: '1',
    }));
    };
//Threshold Filter
$('remove-white-threshold').onchange = function() {
    applyFilterValue(2, 'threshold', this.value);
    };
//Invert Filter
$('invert').onclick = function() {
    applyFilter(1, this.checked && new f.Invert());
  };
})();
// Image Save durch User nach erfolgreicher Bearbeitung  
var imageSaver = document.getElementById('imageSaver');
imageSaver.addEventListener('click', saveImage, false);
 
function saveImage(e) {
    this.href = canvas.toDataURL({
        format: 'jpeg',
        quality: 1
    });
    this.download = 'result.jpeg'
}
});
</script>
```


----------



## Kienz (14. Apr 2015)

I created a small jsfiddle: fabric.js image filters - JSFiddle


----------



## lukme (14. Apr 2015)

Thanks for that man  But how do I combine it with my Imageloader? This is with a static url? Sorry for that question, I am very noob. 
	
	
	
	





```
function handleImage(e) {
        var reader = new FileReader();
        reader.onload = function (event) {
        var img = new Image();
        img.src = event.target.result;
        img.onload = function () {
        var imgInstance = new fabric.Image(img, {
                // If i put it here, it doesnt work
                    scaleY: canvas.height / img.width,
                    scaleX: canvas.width / img.width
        })
        canvas.add(imgInstance);
        }
    }
        reader.readAsDataURL(e.target.files[0]);
   }
```

Thanks in advance.


----------



## Kienz (14. Apr 2015)

I've updated my jsfiddle: fabric.js image filters - JSFiddle


----------



## lukme (14. Apr 2015)

Yeha thanks man, you helped  me a lot! 
Btw. do you have an idea how to autoscale the loaded picture on the size of my canvas height or width?


----------

