Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html canvas: clipping and text

Tags:

html

canvas

clip

I'm working on a paint app using canvas, and i want to let the user the option to draw only in a selected area. for that I can use the clip() method. but if I want the user to be able to draw inside letters also - is there any way to use clip() for text? is there another way I can do it?

thanks

like image 312
Amit Hagin Avatar asked Sep 05 '11 11:09

Amit Hagin


1 Answers

You can do this but not using clip. Clip only works with paths and text is not a path.

You will need to use a second in-memory (not on the page) canvas in order to achieve the effect. Here is how:

  1. Make an in-memory canvas, set it to a width and height capable of containing the text
  2. Draw the text to that in-memory canvas
  3. set the in-memory context's globalCompositeOperation to 'source-in'
  4. Draw the thing you want clipped to the text
  5. use drawImage(in-memory-canvas, x, y) to put the newly created effect onto your normal canvas
like image 145
Simon Sarris Avatar answered Sep 19 '22 13:09

Simon Sarris