<img id="picture" src="https://pbs.twimg.com/media/FXJRT5NUUAAyBKD?format=jpg&name=large" />
<canvas id="card" />
const OCR_API = 'https://api.ocr.space/parse/imageurl?apikey=helloworld&language=chs&isOverlayRequired=true&filetype=jpg';
const img = document.getElementById('picture');
const canvas = document.getElementById("card");
const ctx = canvas.getContext("2d");
const imgWidth = img.width;
const imgHeight = img.height;
const scaleFactor = imgWidth / 1201;
async function imageToText (imageUrl) {
console.log(imageToText);
const res = await fetch(`${OCR_API}&url=${encodeURIComponent(imageUrl)}`, {
method: 'GET',
});
const json = await res.json();
const lines = json['ParsedResults'][0]['TextOverlay']['Lines'];
return lines;
}
async function replaceText(target, replacement, lines) {
const targetLines = lines.filter(line => line.LineText.includes(target));
targetLines.forEach(line => {
line.Words.forEach(word => {
const index = target.indexOf(word.WordText);
if (index != -1) {
const replaceWith = replacement[index];
const targetWord = target[index];
ctx.fillStyle = '#00ff00';
ctx.fillRect(word.Left, word.Top, word.Width, word.Height);
ctx.fillStyle = 'white';
ctx.fillText(replaceWith, word.Left + 2, word.Top + (word.Height / 2));
}
});
});
}
function loadImageIntoCanvas() {
canvas.width = imgWidth;
canvas.height = imgHeight;
ctx.drawImage(img, 0, 0, 1201 * scaleFactor, 1800 * scaleFactor);
ctx.font = 'bold 52px system-ui';
ctx.textBaseline = 'middle';
// call OCR API 返回目標文字位置
imageToText(img.src).then(lines => {
replaceText('安倍', '習總', lines); // replace 標文字
replaceText('安培', '習總', lines);
});
}
loadImageIntoCanvas();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.