Skip to content Skip to sidebar Skip to footer

Different Html Canvas Coordinates

i made 2 deference size html canvas to drawing First canvas = width : 400px,height:200px Second canvas = width : 200px,height :100px Now when i drawing in first html canvas i se

Solution 1:

I hope I have made the right assumptions to answer your question. I created two different canvases of two different sizes. The coordinates only fit on the first, bigger, canvas.

You can transform the 'big' coordinates to 'small' coordinates by dividing the width or height of the bigger smaller canvases by the bigger canvases. For example, the height of the big canvas is 200 but the height of the smaller one is 100. If you divide 100 / 200 you get 0.5. The 'small' coordinates should be half as high as the original ones. See for yourself below:

//just for testing purposes
var coord = {
  x: 320,
  y: 125
};
var ncoord = {
  x: 220,
  y: 90
};

function drawBig() {
  var canvas = document.getElementById("canvas1");
  var ctx = canvas.getContext("2d");
  ctx.beginPath();
  ctx.lineWidth = 5;
  ctx.lineCap = 'round';
  ctx.strokeStyle = "red";
  ctx.moveTo(coord.x, coord.y);
  ctx.lineTo(ncoord.x, ncoord.y);
  ctx.stroke();

}

function drawSmall() {
  let bigCanvas = document.getElementById("canvas1");
  let smallCanvas = document.getElementById("canvas2");

  //Devide the dimensions of the big and small canvas in order to get the magnification factor:
  let widthDimension = smallCanvas.width / bigCanvas.width;
  let heightDimension = smallCanvas.height / bigCanvas.height

  var ctx2 = smallCanvas.getContext("2d");
  ctx2.beginPath();
  ctx2.lineWidth = 5;
  ctx2.lineCap = 'round';
  ctx2.strokeStyle = "red";

  //Transform the original coordinates to the right dimensions:
  ctx2.moveTo(coord.x * widthDimension, coord.y * heightDimension);
  ctx2.lineTo(ncoord.x * widthDimension, ncoord.y * heightDimension);
  ctx2.stroke();

}
canvas {
  border: 1px solid black;
}
<canvas id="canvas1" width="400" height="200"></canvas>
<hr>
<canvas id="canvas2" width="200" height="100"></canvas>


<button onclick="drawBig()">draw big canvas</button>
<button onclick="drawSmall()">draw small canvas</button>

Hope this helps! If not, please comment


Post a Comment for "Different Html Canvas Coordinates"