Tags: javascript canvas
In order to use negative coordinates when drawing with canvas, the most simple way to do this is using translate. There is few caveats. I have made some comments in the code
(You can also se the live example on Codepen: https://codepen.io/diversen/pen/ZyZVpL )
<body>
<script>
window.onload = function () {
console.log('loaded');
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
// Center
ctx.translate(200, 200);
// Add some lines
ctx.beginPath();
ctx.moveTo(-200,0);
ctx.lineTo(200,0);
ctx.stroke();
ctx.moveTo(0,-200);
ctx.lineTo(0, 200);
ctx.stroke();
ctx.font = "12px Arial";
ctx.fillText("+ x",180, -10);
ctx.fillText("- y",10, 180);
ctx.fillText("- x",-200, -10);
ctx.fillText("+ y",10, -180);
// From the above I notice that -x coordinates behaves
// as expected, but the y coordinates jumps on the '
// wrong side of the line.
ctx.fillRect(-100, -100, 4, 4);
ctx.fillText("(-100,-100). Incorrect" ,-100, -100);
// From 'translate' this is correct, but only the x coordinate
// looks like it should:
// x = 200 - 100 = 100
// y = 200 - 100 = 100
// In order to draw correct cartesian coordinates we could make
// a simple function like this
function drawCartesianPoint(ctx, x, y) {
ctx.fillRect(x, -(y), 4, 4);
}
// And for text:
function drawCartesianText(ctx, x, y, text) {
ctx.fillText(text , x, -(y));
}
// Draw corrext:
drawCartesianPoint(ctx, -100, -100);
drawCartesianText(ctx, -100, -100, '(-100, -100) correct');
};
</script>
<canvas id="canvas" width="400" height="400">
</canvas>
This page has been requested 2483 times