我如何从按钮中获取价值并插入到画布中进行填充,例如,如果我按下按钮T,则画布所在的框将用字母T填充整个框的图案,我有一个示例,但我不想复制代码,我想了解它是如何制作的,因为我想做一些更高级的东西,但是我需要首先了解这一点,这里是link example of feature。
答案 0 :(得分:0)
为此,我正在使用3张画布。隐藏了两个画布,但是您无需将它们附加到DOM。逻辑是这样的:
canvas1
),您可以在其中从<textarea>
绘制文本canvas1
创建图案:ctx2.fillStyle = ctx2.createPattern(canvas1,"repeat-x");
,并用它填充第二个画布canvas2
。第二个画布的宽度是主canvas
的两倍。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}
。我希望这会有所帮助。