A Gilani A Gilani - 2 years ago 104
Javascript Question

Division / sub-canvas

I have few coordinates in an XML file. They are lines, circles and arcs. I am reading them in a data structure and then trying to plot them on a canvas. What i am trying to figure out is how to divide the canvas into sub canvases. e.g suppose my canvas is

<canvas id="myCanvas" width="800" height="600" role="img">
Your browser does not support the canvas element.

What I am trying to achieve is how to make an imaginary window of width and height of 200px starting from say x1=200px on canvas and y1=250. And draw the image I have only in that box.

I have managed to scale down the image based on the imaginary box but cannot get around the concept of how to draw only in that imaginary box. The points are randomly distributed.

Answer Source

There are other ways to achieve this but the one you'll probably find most useful in this context is to use translation and a clip mask:

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

/// for simplicity, save current settings

/// move coordinate system to the upper left corner of isolated region
ctx.translate(offsetX, offsetY);

/// create a clipping mask by using a simple rectangle
ctx.rect(0, 0, width, height);

/// define the last path (rectangle) as clipping mask

/// ... draw other things into this region from offset 0...

ctx.restore(); /// done and back to full canvas

By moving the whole coordinate system to the upper left corner of your region you can use offsets relative to the new isolated area. By adding a clip mask anything drawn outside the region will be clipped.

You will need to do this for each region one by one.

Another way is to add an offset to all drawing points. For example:

ctx.lineTo(x + offsetX, y + offsetY);

where offsetX/Y is the upper left corner of the region.

However, it will get more complicated if you need clipping - not a huge issue with images as you can define the destination region but for lines and and other path operation you will need to clip yourself by using interpolation etc.

Here is a live demo demonstrating this:
Fiddle (updated link)

  • The demo sets up a canvas and context and then fills the whole with a red color.
  • Then if sets the clipping and mask and translate it.
  • We now have a "virtual canvas" and the other graphic is intact
  • We now fill the region with the same fill operation but with blue. Now we can see only this regions is filled even the size is outside the actual region
  • Then we remove the clip and draw a line as evidence that we are now back in full mode
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download