meltingice / CamanJS

Javascript HTML5 (Ca)nvas (Man)ipulation

Home Page:http://camanjs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Caman.js render applies to previous state instead of current state of canvas

araGasparyan opened this issue · comments

I am creating a simple image redactor by javascript where the users should be able to rotate an image as well as to apply some filters implemented by Caman js.

I am drawing the initial image in the following canvas:
<canvas id="mainCanvas"></canvas>

In my javascript I have the following code for working with canvas:
var canvasId = 'mainCanvas'; var canvas = document.getElementById(canvasId); var ctx = canvas.getContext('2d');

In order to rotate the image I am using the following function which works as expected:

`function rotate(degree) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();

    var img = new Image();

    img.onload = function() {
        ctx.save();
        ctx.translate(img.width/2, img.height/2);
        ctx.rotate(degree * Math.PI / 180);
        ctx.drawImage(img, -img.width/2, -img.height/2, img.width, img.height);
        ctx.restore();

        processHistory('Rotate');
    };

    img.src = history[lastState];
}`

I can rotate the image multiple times and each time the rotation is applied to the current state of the image/canvas and it works without any problems.

In addition to the rotation, I have a noise button implemented by Caman js as follow:

Caman(canvas, val, function() { this.noise(val).render(function() { processHistory('Noise'); }); });

As in the case of multiple rotations, I can add noise to the image several times and each time the noise is applied to the current state of the image/canvas.

Note that the history in my code is an array for saving the states of manipulated images and the function processHistory is defined as follows:

function processHistory(){ history[lastState] = canvas.toDataURL(); lastState = lastState + 1; }

Problem
Consider the following iteration Noise1 --> Rotation --> Noise2, i.e. apply Noise1 on the original image, follow by applying Rotation and another Noise (Noise2). Then Noise2 (the third step in the pipeline) is not applied to the current state of the image (i. e. the image with Noise1 and Rotation) but to the image with Noise1. I think the problem should be connected with the render function defined in Caman.js, but I am not able to solve it myself. So it is not working as expected, could you please help me to fix my code or give me some ideas about debugging the code.

I could resolve this issue, here is a solution for that:
Just call the rotate function with the following callback:
rotate(1, function() { Caman(canvas, function() { this.reloadCanvasData(); }); });