Invert y value on canvas

Asked

Viewed 107 times

1

I wonder if there is a way to reverse the y axis of the canvas so that the point (0,0) is actually the point (0,500).... That is, if I play the value 20 in the Y, instead of starting from top to bottom, start from bottom to top.....

inserir a descrição da imagem aqui

function altera(valor, ponto) {
  document.getElementById('variavel_' + ponto).innerHTML = valor;

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

  desenhaBase(context, canvas);
}

function desenhaBase(context, canvas) {
  X = document.getElementById('valorX').value;
  Y = document.getElementById('valorY').value;
  X1 = document.getElementById('valorX1').value;
  Y1 = document.getElementById('valorY1').value;
  context.fillStyle = "white";
  context.beginPath();
  context.fillRect(0, 0, canvas.width, canvas.height);
  context.fill();

  context.moveTo(X, Y);
  context.lineTo(X1, Y1);
  context.strokeStyle = 'blue';
  context.stroke();
}
<table>
  <tr>
    <td>&nbsp;&nbsp;&nbsp;&nbsp;x1: <span id="variavel_x"></span>
    </td>
    <td>y1: <span id="variavel_y"></span>
    </td>
  </tr>
  <tr>
    <td>
      <input type="range" style="width: 180px;" name="x" id="valorX" min="0" max="375" oninput="altera(this.value,this.name)">
    </td>
    <td>
      <input type="range" style="width: 180px;" name="y" id="valorY" min="0" max="500" oninput="altera(this.value,this.name)">
    </td>
  </tr>
  <tr>
    <td>&nbsp;&nbsp;&nbsp;&nbsp;x2: <span id="variavel_x1"></span>
    </td>
    <td>y2: <span id="variavel_y1"></span>
    </td>
  </tr>
  <tr>
    <td>
      <input type="range" style="width: 180px;" name="x1" id="valorX1" min="0" max="375" oninput="altera(this.value,this.name)">
    </td>
    <td>
      <input type="range" style="width: 180px;" name="y1" id="valorY1" min="0" max="500" oninput="altera(this.value,this.name)">
    </td>
  </tr>
</table>
<canvas id="myCanvas" width="375" height="500"></canvas>

1 answer

2


If I understand your question you only need to know the height of the canvas canvas.height and subtract from that number the Y, that is to say: context.moveTo(X, canvas.height - Y);

jsFiddle: http://jsfiddle.net/4mr6jqc/

  • well, with a little caveat @Sergio at the bottom line, where you define Y1 should also subtract the height, then it’s perfect: (X1, canvas.height - Y1); http://jsfiddle.net/4mr6jqqc/1/

Browser other questions tagged

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