Acquiring coordinates in Javascript with the help of the CamanJs library

2

I'm here creating an image editor using Javascript with the CamanJs library and the HTML5 canvas element, but I'm not able to do it draw a box over my image (it disappears as it begins to draw); <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();
    });
    
asked by anonymous 10.04.2014 / 06:58

1 answer

2

Since CamanJS itself creates a canvas with its image, it is not necessary to create another - this only brings additional complication. I suggest using the canvas itself and drawing it over - 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 crop (in mouseUp I render again, to clear the rectangle, I call crop and render it one more time, pro crop to have effect), but since I'm not familiar with this library, I did not want too much ...

    
10.04.2014 / 13:41