Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change out an image using CamanJS?

I've got multiple images, and I'd like to load them each into a single <canvas> element at different points in time and then manipulate them using CamanJS. I can get the first image to appear like this:

Caman('#canvas-element', '/images/one.jpg');

But then when I subsequently try to update that same element using the following code, it does not work.

Caman('#canvas-element', '/images/two.jpg');

Is there some way to reset/clear/flush the canvas and load new image data into it, or do I really need to create separate <canvas> elements for each image I want to load? I'd prefer a single element because I don't want to eat up all the memory.

like image 991
soapergem Avatar asked Feb 22 '13 20:02

soapergem


3 Answers

Remove the Caman attribute (data-caman-id) from the IMG or CANVAS element, change the image, and then re-render Caman.

document
  .querySelector('#view_image')
  .removeAttribute('data-caman-id');

const switch_img = '/to/dir/img.png';

Caman("#view_image", switch_img, function() {
  this.render();
});
like image 52
neurosnap Avatar answered Nov 11 '22 09:11

neurosnap


Hope followed code can help others who have same require.

function loadImage(source) {
    var canvas = document.getElementById('image_id');
    var context = canvas.getContext('2d');
    var image = new Image();
    image.onload = function() {
        context.drawImage(image, 0, 0, 960, 600);
    };
    image.src = source;
}

function change_image(source) {
    loadImage(source);
    Caman('#image_id', source, function () {
        this.reloadCanvasData();
         this.exposure(-10);
         this.brightness(5);
        this.render();
    });
}
like image 26
Arthur Avatar answered Nov 11 '22 09:11

Arthur


Just figured this one out with a lot of trial and error and then a duh moment!

Instead of creating my canvas directly in my html, I created a container and then just did the following:

var retStr = "<canvas id=\"" + myName + "Canvas\"></canvas>";
document.getElementById('photoFilterCanvasContainer').innerHTML = retStr;

Caman("#" + myName + "Canvas", myUrl, function() {
    this.render();
});

You want the canvas id to be unique each time you access the Caman function with a new image.

like image 1
user2253389 Avatar answered Nov 11 '22 07:11

user2253389