Reputation: 143
Starting point of a canvas is top left corner that is x,y(0,0). I can plot positive values on canvas.
Below is my sample code
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>
but i can't plot x and y if value of x and y is negative. Code below is not working
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(-200,-100);
ctx.stroke();
</script>
I want to plot negative values on canvas. Is this possible?
this is what i want
Upvotes: 4
Views: 2410
Reputation: 54089
You can position the origin (0,0) where ever you like with either, ctx.translate
, ctx.transform
, or ctx.setTransform
.
ctx.translate
, ctx.transform
are relative to the current transform. ctx.setTransform
is absolute.
The easiest way I find is to use ctx.setTransform
const W = ctx.canvas.width, H = ctx.canvas.height;
ctx.setTransform(1,0,0,1,0,0); // resets the transform to clear
ctx.clearRect(0,0,W,H); // clears the canvas
ctx.setTransform(1, 0, 0, 1, W / 2, H / 2); // moves the origin to the center of
// the canvas
ctx.strokeRect(-200,-200, 190, 190);
The 6 arguments for setTransform
are.
x : 1, y : 0
x : 0, y : 1
Thus you can scale by changing the first four
ctx.setTransform(2, 0, 0, 2, W / 2, H / 2); // zooms in by 2 with origin at center
ctx.setTransform(0.5, 0, 0, 0.5, W / 2, H / 2); // zooms out by 2 with origin at center
Upvotes: 1