0

JSFiddle: https://jsfiddle.net/09a7kb32/

I have a page with a Header DIV (height: 50px) and a Canvas DIV (whose height occupies the remainder of the screen). I'm using PaperJS to draw a circle which is the full size of the (lower) Canvas DIV. However, the center X/Y coordinate doesn't seem to be obeyed, even though it should be getting calculated correctly. I'm getting the circle drawn lower than it should be, with an empty vertical gap between the Header and the Canvas, whereas it should be touching the header directly.

canvasElem = $('#canvas').get(0);
paper.setup(canvasElem);

var offset = $('#canvasPanel').offset(); 
var width = $('#canvasPanel').width(); 
var height = $('#canvasPanel').height();

var centerX = offset.left + width / 2;   // CenterX is left offset of Header DIV (actually 0) + CanvasPanel's half-width
var centerY = offset.top + height / 2;   // CenterY is top offset of Header DIV (15px) + CanvasPanel's half-height

// Let the radius be the smaller of the width/height, divided by 2
var radius = Math.min(width,height) / 2;

var circle = new paper.Path.Circle(new paper.Point(centerX,centerY), radius);
circle.fillColor = 'white';
circle.strokeColor = 'black';
paper.view.draw();

CSS: To get the top/bottom DIVs to span the entire vertical screen, absolute positioning is used, as suggested here. Also, the canvas itself is 100%/100%.

#headerPanel {
    border-bottom: 1px solid black;
    width: 100%;
    height: 50px;
}

#canvasPanel {
  position: absolute;
  width:100%;
  top:50px;
  bottom:0;
}

#canvas {
    width: 100%;
    height: 100%;
}

HTML

<div id="headerPanel">
    Text
</div>

<div id="canvasPanel">
    <canvas id="canvas" resize></canvas>
</div>
gene b.
  • 10,512
  • 21
  • 115
  • 227

1 Answers1

1

If you would like to draw a circle in the center of a paperjs View(canvas), heres how I would do it:

  const scope = new paper.PaperScope();
  project = new scope.Project(canvasElem);
  const centerOfCanvas = scope.view.center; // this is the center of the paperjs view/canvas
  const radius = Math.min(scope.view.bounds.width,scope.view.bounds.height) / 2;    
  const circle = new paper.Path.Circle(centerOfCanvas, radius);

You are trying to apply values derived from the canvas css position and width to the paperjs view(canvas) which I dont believe is a 1x1 comparison.

Hozeis
  • 1,542
  • 15
  • 36
  • Thanks, I figured out why there is a gap. The coordinates are not DIV-relative, they are absolute in terms of the screen. So I had to subtract the height of my 1st DIV, 15px. – gene b. Jun 06 '22 at 23:48