meltingice / CamanJS

Javascript HTML5 (Ca)nvas (Man)ipulation
http://camanjs.com
BSD 3-Clause "New" or "Revised" License
3.56k stars 406 forks source link

Caman clear all canvas #210

Closed nthhtn closed 8 years ago

nthhtn commented 8 years ago

Question on Stackoverflow here

When I try to apply filter on already created canvas element, it clear my canvas and does not render anything

nthhtn commented 8 years ago

I already found a solution for that. It was because of my error on asynchronous handling. It should be like this

var brightnessSlider=document.getElementById('brightnessSlider');
noUiSlider.create(brightnessSlider,{
    start: 0,
    step: 1,
    connect: 'lower',
    range: {
        min: -100,
        max: 100
    },
    format: wNumb({
        decimals: 0
    })
});

(function(){

    // Upload, resize image, draw canvas

    function fileOnload(e) {
        var img=new Image;
        img.src=e.target.result;
        var canvas=document.getElementById('edit-canvas');
        var context=canvas.getContext('2d');
        img.onload=function(){
            canvas.height=canvas.width * img.height / img.width;
            var oc = document.createElement('canvas'), octx = oc.getContext('2d');
            oc.width = img.width;
            oc.height = img.height;
            octx.drawImage(img, 0, 0);
            while (oc.width * 0.5 > canvas.width) {
                oc.width *= 0.5;
                oc.height *= 0.5;
                octx.drawImage(oc, 0, 0, oc.width, oc.height);
            }
            oc.width = canvas.width;
            oc.height = oc.width * img.height / img.width;
            context.drawImage(img, 0, 0, oc.width, oc.height);
            Caman('#edit-canvas',function(){
                this.render();
            });

            brightnessSlider.noUiSlider.on('change',function(values,handle){
                $('#brightness').html(values[handle]);
                Caman('#edit-canvas',function(){
                    this.revert(false);
                    this.brightness(values[handle]).render();
                });
            });
        };
    };

    $('#upload-image').change(function(e){
        var file = e.target.files[0];
        var imageType = /image.*/;
        if (!file.type.match(imageType))
            return;
        var reader = new FileReader();
        reader.onload = fileOnload;
        reader.readAsDataURL(file);
    });
})();