Search code examples
javascripthtmlcanvascamanjs

Camanjs clear canvas when init Caman()?


I apply Caman Filter to a canvas with existing image data. But when I create Caman object to use later, it emply my canvas.

var ca = Caman('#myCanvas');

I'm try to do exactly with Caman Guide , like this:

Caman('#myCanvas',function(){
   this.render();
});

But the same problem, canvas is clear! Why I cannot load canvas to Caman then modify, although documentation says can be?


Solution

  • You don't need to grab a reference to the Caman object with: var ca = Caman("#myCanvas");

    First, draw something on the original canvas:

    // make a drawing on the original canvas
    
    var canvas=document.getElementById("myCanvas");
    var ctx=canvas.getContext("2d");
    ctx.fillStyle="red";
    ctx.fillRect(20,20,60,40);
    

    Then tell Caman to use #myCanvas as both the source and destination for any filters:

    // modify the original drawing from #myCanvas and put it back on #myCanvas
    
    Caman("#myCanvas",function(){
        this.brightness(50).render();
    });
    

    About your cleared canvas:

    Since Caman uses .getImageData, be sure your image is hosted on the same site as the web page you're serving otherwise a CORS security violation will cause your canvas to be blank.

    var canvas = document.getElementById("original");
    var ctx = canvas.getContext("2d");
    
    // make a drawing on the original canvas
    ctx.fillStyle = "blue";
    ctx.fillRect(20, 20, 60, 40);
    
    // modify the original drawing 
    Caman("#original", function () {
        this.brightness(75).render();
    });
    <script src="http://cdnjs.cloudflare.com/ajax/libs/camanjs/4.0.0/caman.full.min.js"></script>
    <canvas id="original" width=100 height=100></canvas>