Tijo Titus
Tijo Titus

Reputation: 143

How to plot negative x and y values on canvas

Starting point of a canvas is top left corner that is x,y(0,0). I can plot positive values on canvas.

enter image description here

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

enter image description here

Upvotes: 4

Views: 2410

Answers (1)

Blindman67
Blindman67

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.

  • first 2 the vector describing the top edge of a rendered pixel. The X axis x : 1, y : 0
  • second 2 the vector describing the left edge of a rendered pixel. The Y axis x : 0, y : 1
  • last 2 the location in canvas pixels, of the top left of rendered pixel 0,0

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

Related Questions