Acquiring Javascript coordinates with the help of the Camanjs library

Asked

Viewed 240 times

2

I am here creating an image editor using Javascript with the help of the library Camanjs and the HTML5 canvas element, but I’m not getting him to draw a box on top of my image (it disappears as soon as he starts drawing); <canvas id="cavas-id"></canvas>. I thought of something like canvas inside canvas, but my background turns white.

var canvas = document.getElementById('crop'),
ctx = canvas.getContext('2d'),
rect = {},
drag = false;

function init() {
  canvas.addEventListener('mousedown', mouseDown, false);
  canvas.addEventListener('mouseup', mouseUp, false);
  canvas.addEventListener('mousemove', mouseMove, false);
}

function mouseDown(e) {
  alert('asd');
  rect.startX = e.pageX - this.offsetLeft;
  rect.startY = e.pageY - this.offsetTop;
  drag = true;
}

function mouseUp() {
  drag = false;
}

function mouseMove(e) {
  if (drag) {
    rect.w = (e.pageX - this.offsetLeft) - rect.startX;
    rect.h = (e.pageY - this.offsetTop) - rect.startY ;
    ctx.clearRect(0,0,canvas.width,canvas.height);
    draw();
  }
}

function draw() {
  ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
init();

And my image:

Caman('#canvas-id', 'balanco.jpg', function()
    {

        this.render();
    });
  • I am unable to reproduce your problem. Which browser are you using? I tested the following example in Chrome, and it worked perfectly (i.e. by clicking and dragging on the image, a black rectangle appears on it): http://jsfiddle.net/mgibsonbr/v3A3R/1/ (Note: I used an image in Base64 because I couldn’t test an image in a crossed domain, but the end result is the same - Caman transforms the img in canvas)

1 answer

2


How Camanjs himself creates a canvas With your image, it’s not necessary to create another one - it just brings additional complication. I suggest using the canvas itself and drawing on top - right after the image is rendered:

var caman = Caman('#canvas-id', 'balanco.jpg', function()
{
    this.render();
    canvas = this.canvas; // Salva uma referência para o canvas
    ctx = this.context;   // e para o contexto
    init(); // Só então inicializa
});

var canvas, ctx, rect = {}, drag = false; // Inicialmente, canvas e ctx são vazios

...

function draw() {
  // Desenhe a imagem e, quando ela estiver pronta...
  caman.render(function() {
      // ... desenhe o retângulo por cima
      ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
  });
}
//init(); // Não pode inicializar agora, pois o canvas ainda não está pronto

Example in jsFiddle. In this example I still do a rudimentary Rop (no mouseUp I rewrite, to clear the rectangle, I call the crop And I’ve rewritten it once again, so Crop takes effect), but since I’m not familiar with this library, I didn’t overdo it...

  • I work perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.