【问题标题】:pattern background text with canvas带画布的图案背景文本
【发布时间】:2019-04-27 21:45:45
【问题描述】:

我如何从按钮中获取值并插入到画布中进行填充,例如,如果我按下按钮 T,画布所在的框将用字母 T 整个框填充图案,我有一个示例,但我不想要复制代码我想了解它是如何制作的,因为我想做更高级的东西,但我需要先了解这一点,这里是link example of feature

【问题讨论】:

    标签: javascript jquery html5-canvas


    【解决方案1】:

    为此,我使用了 3 个画布。隐藏了两个画布,但您不需要将它们附加到 DOM。逻辑是这样的:

    1. 您有第一个画布 (canvas1),您可以在其中从 <textarea> 绘制文本
    2. 您使用canvas1: ctx2.fillStyle = ctx2.createPattern(canvas1,"repeat-x"); 创建了一个图案,并使用它来填充第二个画布canvas2。第二张画布的宽度是主要的canvas 的两倍。
    3. 您使用canvas2 作为主canvas 的背景图像在这里您可以使用循环。我没有。

    let fontSize = 50;
    const canvas = document.querySelector("canvas");
    const canvas1 = document.createElement("canvas");
    const canvas2 = document.createElement("canvas");
    
    test.appendChild(canvas1);// you don't need to attach this to the DOM
    test.appendChild(canvas2);// you don't need to attach this to the DOM
    canvas.width = 500;
    canvas.height = fontSize * 4;
    canvas1.height = fontSize;
    canvas2.height = fontSize;
    canvas2.width = 2*canvas.width;
    let ctx = canvas.getContext("2d");
    let ctx1 = canvas1.getContext("2d");
    let ctx2 = canvas2.getContext("2d");
    
    ctx1.font = fontSize+"px 'Lucida Console', monospace";
    
            
    theText.addEventListener("input",()=>{
      ctx2.clearRect(0,0, canvas2.width, canvas2.height);
      ctx.clearRect(0,0, canvas.width, canvas.height);
      let _text = theText.value.toUpperCase();
    
      let textLength = ctx1.measureText(_text).width;
      canvas1.width = textLength || 1;// to avoid width 0 of the canvas
      ctx1.font = fontSize+"px 'Lucida Console', monospace";
      ctx1.fillStyle = "blue";
      ctx1.textBaseline="middle"; 
      ctx1.fillText(_text, 0, canvas1.height/2);
      
      ctx2.fillStyle = ctx2.createPattern(canvas1,"repeat-x");
      
      ctx2.fillRect(0,0, canvas2.width, canvas2.height);
      
      ctx.drawImage( canvas2, 0, 0 );
      ctx.drawImage( canvas2, -canvas2.width/2, fontSize );
      ctx.drawImage( canvas2, canvas2.width/2, fontSize );
      ctx.drawImage( canvas2, 0, 2*fontSize );
      ctx.drawImage( canvas2, -canvas2.width/2, 3*fontSize );
      ctx.drawImage( canvas2, canvas2.width/2, 3*fontSize );
    })
    canvas{border:1px solid;}
    #test{display:none}
    <canvas></canvas>
    <textarea id="theText"></textarea>
    <div id="test"></div>

    为了更好地理解发生了什么,请从 css 中删除 #test{display:none}。我希望这会有所帮助。

    【讨论】:

    • 你太棒了,可以pm我或联系你吗?
    猜你喜欢
    • 2021-02-14
    • 2014-05-22
    • 2013-09-24
    • 2015-03-18
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    相关资源
    最近更新 更多