可添加背景杂质和文字扭曲变形,效果如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Text Anti-OCR</title> <style> .anti-ocr-canvas { background-color: #f0f0f0; border: 1px solid #ccc; } </style> </head> <body> <canvas id="anti-ocr-canvas" width="400" height="100"></canvas> <script> function drawTextToCanvas(text, canvasId) { let canvas = document.getElementById(canvasId); let ctx = canvas.getContext('2d'); // 添加背景杂质 for (let i = 0; i < 1000; i++) { let x = Math.random() * canvas.width; let y = Math.random() * canvas.height; ctx.fillStyle = `rgba(14, 12, 123, ${Math.random() * 0.8})`; ctx.fillRect(x, y, 1, 1); } // 设置文字样式 ctx.font = '20px Arial'; ctx.fillStyle = '#333'; // 扭曲文字 let chars = text.split(''); let x = 10; let y = 50; for (let i = 0; i < chars.length; i++) { ctx.save(); ctx.translate(x, y); ctx.rotate(Math.random() * 0.7 - 0.1); ctx.fillText(chars[i], 0, 0); ctx.restore(); x += ctx.measureText(chars[i]).width + Math.random() * 4 - 2; } } drawTextToCanvas('这是一个防止OCR识别的文本。', 'anti-ocr-canvas'); </script> </body> </html>
网友回复