How to display image under text like as a background?

前端 未结 4 869
再見小時候
再見小時候 2021-01-06 12:51

I want to display Image under Text. I have done this with Photoshop but it\'s a Image. So every time text change I have to do changes in Photoshop. I want to achieve same us

4条回答
  •  一向
    一向 (楼主)
    2021-01-06 13:16

    Canvas

    This is not using CSS as requested but the canvas element.

    The following example will clip the image by the text as well as add a shadow to it.

    Example

    LIVE DEMO HERE

    The result from doing this will be:

    demo snapshot

    /// set some text settings
    ctx.textBaseline = 'top';  /// defaults to baseline, using top makes life simpler
    ctx.font = '150px impact'; /// set the font and size we want to use
    ctx.textAlign = 'center';  /// center for example
    
    /// next draw the text
    ctx.fillText(txt, demo.width * 0.5, 10);
    

    Next step is to change the composite mode so we use the already drawn text as clipping for the next thing we draw:

    /// change composite mode to fill text
    ctx.globalCompositeOperation = 'source-in';
    
    /// draw the image you want on top; will be clipped by text
    ctx.drawImage(img, 0, 0);
    

    Now the image we drew got clipped. To add a shadow we need to go an extra round as if we added shadow from the beginning the images would have been drawn into the shadow area as well.

    So what we need to do is to reset composite mode to default, set shadow and then draw the canvas back to itself. As it's drawn on top in the exact same position we won't notice.

    We are using save and restore here to avoid resetting the shadow manually.

    /// reset composite mode to normal
    ctx.globalCompositeOperation = 'source-over';
    
    /// create a shadow by setting shadow...
    ctx.save();
    ctx.shadowColor = 'rgba(0,0,0,0.5)';
    ctx.shadowBlur = 7;
    ctx.shadowOffsetX = 3;
    ctx.shadowOffsetY = 3;
    
    /// ... and drawing it self back
    ctx.drawImage(demo, 0, 0);
    ctx.restore();
    

    In the demo I made a loop that changes the text so you can see that it's simply a matter of supplying a different text.

    Also notice that the background is transparent so you can place the canvas on top of other elements (in the demo I changed the background color of the body).

    I would suggest that the demo code is refactored to a universal function instead. For that you can put all settings inside it and move save to the beginning and restore to the end in order to preserve other settings set outside the function.

提交回复
热议问题