<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas Text Input</title> </head> <body> <input type="text" id="textInput" placeholder="Enter text..."> <button onclick="drawText()">Draw Text</button> <canvas id="myCanvas" width="400" height="200"></canvas> <script src="script.js"></script> </body> </html>
function drawText() { // 获取canvas元素和上下文 const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // 清除之前的绘制内容 ctx.clearRect(0, 0, canvas.width, canvas.height); // 获取输入文本 const textInput = document.getElementById('textInput'); const text = textInput.value; // 设置字体和样式(可选) ctx.font = '30px Arial'; ctx.fillStyle = 'black'; // 测量文本宽度(可选,用于居中或其他布局) const textWidth = ctx.measureText(text).width; // 在canvas上绘制文本 // 例如,我们将其绘制在中心位置 const x = (canvas.width - textWidth) / 2; const y = canvas.height / 2 + 15; // 加一些间距以便看到文本基线 ctx.fillText(text, x, y); }
function drawText() { // 获取canvas元素和上下文 const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // 清除之前的绘制内容 ctx.clearRect(0, 0, canvas.width, canvas.height); // 获取输入文本 const textInput = document.getElementById('textInput'); const text = textInput.value; // 设置字体和样式(可选) ctx.font = '30px Arial'; ctx.fillStyle = 'black'; // 测量文本宽度(可选,用于居中或其他布局) const textWidth = ctx.measureText(text).width; // 在canvas上绘制文本 // 例如,我们将其绘制在中心位置 const x = (canvas.width - textWidth) / 2; const y = canvas.height / 2 + 15; // 加一些间距以便看到文本基线 ctx.fillText(text, x, y); }