3

I am trying to write the description of each edge along the rectangle. The reason is to describe the length of each edge inside and outside rectangles (alongside). Is there a way I can achieve it?

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Clip a rectangular area
ctx.rect(50, 20, 200, 120);
ctx.stroke();
ctx.clip();
// Draw red rectangle after clip()
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 150, 100);

This should show 200 above the top edge (outside) and 150 along the left edge (outside)

stealththeninja
  • 3,576
  • 1
  • 26
  • 44
Code Guy
  • 3,059
  • 2
  • 30
  • 74

1 Answers1

4

Using @stealththeninja's comment (pointing to this answer - text in html canvas) and this jsfiddle (for text rotation), I was able to build the code below. Hope it fits within your specs.

Screenshot of the result attached. html canvas text rotated

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");

    const rectPosX = 50;
    const rectPosY = 50;
    const rectLength = 200;
    const rectHeight = 150;

    ctx.fillStyle = "red";
    ctx.fillRect(rectPosX, rectPosY, rectLength, rectHeight);

    ctx.fillStyle = "blue";
    ctx.fillText('200', rectPosX + rectLength / 2, rectPosY);
    ctx.fillText('150', rectPosX, rectPosY + rectHeight / 2);
    ctx.fillText('200', rectPosX  + rectLength / 2, rectPosY + rectHeight);

    ctx.save();
    ctx.translate(rectPosX + rectLength, rectPosY + rectHeight / 2);
    ctx.rotate(0.5*Math.PI);
    ctx.fillText('150', 0, 0);
    ctx.restore();
<canvas id="myCanvas" width="400" height="300"></canvas>
Artem K
  • 169
  • 1
  • 1
  • 9