简体   繁体   中英

How to slowly fill text on html5 canvas

I currently have text on a canvas that is white. I would like to be able to slowly and smoothly fill the text with another color (red) from left to right. Is there a way to do this so at times a letter will be white on a fraction and red on the other side?

An example using the word "Color".

The "Col" are red. The next "o" has 25% red (left) and 75% white (right). The "r" is full white.

Update

Thanks for all the help. I noticed it works even better if you add ctx.beginPath() before the clip object.

I have added a little bit to the idea and created a small js object that seems to work nicely for my current project. It may not be the most elegant js but hopefully it helps out someone else that wants to do this later. There is a slight issue I noticed with the size of text changing when it starts to fill, not sure why. http://jsfiddle.net/WRAFA/4/

You can do this whit the composite operation source-in. If you first draw your text with your background color (white) with composite operation source-over and then draws a colored-rect over it with soruce-in its only intersection between the text and rect that will be drawn. I made a small example at jsfiddle

Nice job on fixing Richard's fiddle. I've made a couple improvements.

  1. you asked for a black canvas background with white text.
  2. The use of setInterval is not recommended here. You are running draw for ever and ever and ever and ever and ever and.... I have fixed the fiddle to use setTimeout so that it stops the draw events as soon as you get to the edge of the canvas.

The adjusted fiddle is at http://jsfiddle.net/d4Jef/1/

One thing I would recommend, though. Instead of using compositing, you should write text using a clipping region . The problem with source-in compositing is that if your text were written over some kind of image with opaque pixels, then filling a rect over this would blow away your background. You got away with it here because you had nothing else on your canvas except the text. So it's better to go with a clipping region.

Here is the version with the clipping approach: http://jsfiddle.net/5ZgNz/2/

Note the use of the additional green square to highlight which this approach works in general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM