1

My problem is simple. I just want to make invisible text parts when it's out of my rectangle. This image will help to understand what I want. How can I make invisible gray parts of text at canvas? Thanks for help! enter image description here

RepahidiS
  • 45
  • 8
  • 1
    This might be applicable: https://stackoverflow.com/questions/10616668/how-to-hide-canvas-content-from-parent-rounded-corners-in-any-webkit-for-mac – nbwoodward Nov 06 '18 at 20:08
  • 1
    Yes but I don't want solve it with css because my project is on canvas completely. – RepahidiS Nov 06 '18 at 20:12

2 Answers2

3

After drawing your rectangle, invoke

ctx.clip();

Then draw the parts that should be only inside it.

Source

Daniel Rothig
  • 696
  • 3
  • 10
2

I would use ctx.globalCompositeOperation = "source-atop"

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 400;
let ch = canvas.height = 110;
ctx.fillStyle = "#ccc";

ctx.beginPath();
ctx.fillRect(100,25,200,60);

ctx.globalCompositeOperation = "source-atop"
ctx.font="2em Verdana";
ctx.fillStyle = "#f00";

ctx.fillText("This is some text",110,65);
canvas{border:1px solid;}
<canvas id="canvas"></canvas>
enxaneta
  • 31,608
  • 5
  • 29
  • 42