Canvas Text with Outline
哈哈哈,沒錯!既然你的 PNG 文字本身就是用 Canvas 產生的,那直接在 Canvas 生成時就加上邊框,絕對是最高效、最根本的解決方法!這樣可以避免 Procreate 裡的點陣圖操作可能產生的鋸齒或模糊問題,也能保持向量文字的清晰度。
先畫邊框 (Stroke): 設定好邊框的顏色 (strokeStyle) 和粗細 (lineWidth),然後使用 strokeText() 繪製文字的輪廓。再畫填充 (Fill): 設定好文字內部的顏色 (fillStyle),然後使用 fillText() 在相同位置 繪製文字的填充部分。
<!DOCTYPE html>
<html>
<head>
<title>Canvas Text with Outline</title>
<style>
body { margin: 20px; background-color: #f0f0f0; }
canvas { border: 1px solid black; background-color: white; }
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// --- 設定 ---
const text = "原來如此!";
const x = canvas.width / 2; // 文字水平中心
const y = canvas.height / 2; // 文字垂直中心
const fontSize = 60;
const fontFamily = 'Arial, sans-serif'; // 選擇你想要的字體
const fontWeight = 'bold'; // 'normal', 'bold', etc.
const fillColor = '#333333'; // 文字填充顏色 (例如: 深灰色)
const strokeColor = '#FFD700'; // 邊框顏色 (例如: 金色)
const lineWidth = 4; // 邊框粗細 (像素)
// --- 設定 Canvas Context 屬性 ---
ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
ctx.textAlign = 'center'; // 水平居中
ctx.textBaseline = 'middle'; // 垂直居中
// 設定邊框樣式
ctx.strokeStyle = strokeColor;
ctx.lineWidth = lineWidth;
// ctx.lineJoin = 'round'; // 讓線條連接處更圓滑 ('miter', 'round', 'bevel')
// 設定填充樣式
ctx.fillStyle = fillColor;
// --- 繪製 ---
// 1. 先畫邊框
ctx.strokeText(text, x, y);
// 2. 再畫填充 (在相同位置)
ctx.fillText(text, x, y);
// --- (可選) 匯出 PNG ---
// 如果你需要直接從這裡產生 PNG,可以在繪製完成後:
// const dataURL = canvas.toDataURL('image/png');
// console.log(dataURL); // 你可以在控制台看到 base64 的 PNG 數據
// 或者創建一個圖片元素顯示/下載
// const img = new Image();
// img.src = dataURL;
// document.body.appendChild(img);
</script>
</body>
</html>
HTML 結構: 包含一個 <canvas> 元素。獲取 Context: canvas.getContext('2d')。設定參數: 自訂文字內容、位置、字體大小/樣式、填充顏色、邊框顏色和邊框粗細。設定 Context 屬性: ctx.font: 設定字體樣式和大小。 ctx.textAlign, ctx.textBaseline: 設定文字對齊方式,方便定位。 ctx.strokeStyle, ctx.lineWidth: 設定邊框顏色和寬度。 ctx.lineJoin (可選): 控制線條轉角處的樣式,'round' 通常效果不錯。 ctx.fillStyle: 設定文字內部填充顏色。
繪製: 先呼叫 ctx.strokeText(text, x, y); 畫邊框。 再呼叫 ctx.fillText(text, x, y); 畫填充。
匯出 (可選): 可以使用 canvas.toDataURL('image/png') 將 Canvas 內容匯出為 Base64 格式的 PNG 數據,你可以用這個數據來創建圖像或進行下載。
留言
張貼留言