zklim
zklim

Reputation: 525

HTML5 Canvas not Aligned

So, I have the following code as HTML:

<canvas id='myCanvas'></canvas>
<span id='coords'></span>
<button class='clear'>clear</button>

The CSS to go with it:

#myCanvas{
  width: 278px;
  height: 100px;
  border-left: 2px solid black;
  border-bottom: 2px solid black;
}

And some Javascript:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var mouseClicked = false;

function writeMessage(canvas, message) {
  $('#coords').text(message);
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

$(document).on({
  'mousedown':function(){
    mouseClicked=true;
  },
  'mouseup':function(){
    mouseClicked=false;
  }
})

$('#myCanvas').on({
  'mousemove':function(evt){
    if(mouseClicked){
        var mousePos = getMousePos(canvas, evt);
        var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
        writeMessage(canvas, message);
      context.beginPath();
      context.rect(mousePos.x, mousePos.y, 1, 1);
      context.fillStyle = 'black';
      context.fill();
      context.lineWidth = 1;
      context.strokeStyle = 'black';
      context.stroke();
    }
  },
  'mousedown':function(evt){
    var mousePos = getMousePos(canvas, evt);
    var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
    writeMessage(canvas, message);
  }
});

// Clear canvas
$('.clear').click(function(){
  context.clearRect(0, 0, canvas.width, canvas.height);
});

// make other text non selectable
$('#coords').disableSelection();

The problem I'm having is when I draw on the canvas, the small squares I'm drawing don't line up with where the cursor is currently at. It's almost as if there's some sort of vertical/horizontal scaling problem, but I'm not sure how to fix it.

Upvotes: 0

Views: 607

Answers (1)

EaziLuizi
EaziLuizi

Reputation: 1615

You are almost there, just change your getMousePos function to this:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {

        x: Math.round((evt.clientX-rect.left)/(rect.right-rect.left)*canvas.width),
        y: Math.round((evt.clientY-rect.top)/(rect.bottom-rect.top)*canvas.height)
    };
}

This way your calc and mouse positions are relative to the canvas, which is what i believe you are looking for?

Upvotes: 4

Related Questions