Transparent text cut out of background

后端 未结 12 704
无人及你
无人及你 2020-11-22 06:05

Is there any way to make a transparent text cut out of a background effect like the one in the following image, with CSS?
It would be sad to lose all pr

12条回答
  •  -上瘾入骨i
    2020-11-22 06:34

    I needed to make text that looked exactly like it does in the original post, but I couldn't just fake it by lining up backgrounds, because there's some animation behind the element. Nobody seems to have suggested this yet, so here's what I did: (Tried to make it as easy to read as possible.)

    var el = document.body; //Parent Element. Text is centered inside.
    var mainText = "THIS IS THE FIRST LINE"; //Header Text.
    var subText = "THIS TEXT HAS A KNOCKOUT EFFECT"; //Knockout Text.
    var fontF = "Roboto, Arial"; //Font to use.
    var mSize = 42; //Text size.
    
    //Centered text display:
    var tBox = centeredDiv(el), txtMain = mkDiv(tBox, mainText), txtSub = mkDiv(tBox),
    ts = tBox.style, stLen = textWidth(subText, fontF, mSize)+5; ts.color = "#fff";
    ts.font = mSize+"pt "+fontF; ts.fontWeight = 100; txtSub.style.fontWeight = 400;
    
    //Generate subtext SVG for knockout effect:
    txtSub.innerHTML =
    ""+
        ""+
        ""+
            ""+
            ""+subText+""+
        ""+
    "";
    
    //Relevant Helper Functions:
    function centeredDiv(parent) {
        //Container:
        var d = document.createElement('div'), s = d.style;
        s.display = "table"; s.position = "relative"; s.zIndex = 999;
        s.top = s.left = 0; s.width = s.height = "100%";
        //Content Box:
        var k = document.createElement('div'), j = k.style;
        j.display = "table-cell"; j.verticalAlign = "middle";
        j.textAlign = "center"; d.appendChild(k);
        parent.appendChild(d); return k;
    }
    function mkDiv(parent, tCont) {
        var d = document.createElement('div');
        if(tCont) d.textContent = tCont;
        parent.appendChild(d); return d;
    }
    function textWidth(text, font, size) {
        var canvas = window.textWidthCanvas || (window.textWidthCanvas = document.createElement("canvas")),
        context = canvas.getContext("2d"); context.font = size+(typeof size=="string"?" ":"pt ")+font;
        return context.measureText(text).width;
    }
    

    Just throw that in your window.onload, set the body's background to your image, and watch the magic happen!

提交回复
热议问题