我有两个文本区域位于画布的顶部和底部。
当你输入时,我需要文本到达画布边缘然后闯入一个新行。
但是,当您键入新单词时,它会分成一个新行。如果这个词很长,它会浓缩这个词的外观(与拉伸它相反。)
这是我的代码:
let topTextInput, bottomTextInput, topTextSizeInput, bottomTextSizeInput, imageInput, generateBtn, canvas, ctx;
function generateMeme (img, topText, bottomText, topTextSize, bottomTextSize) {
let fontSize;
// Size canvas to image
canvas.width = 800;
canvas.height = 800;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw main image
ctx.drawImage(img, 0, 0);
// Text style: white with black borders
ctx.fillStyle = 'white';
ctx.strokeStyle = 'black';
ctx.textAlign = 'center';
ctx.lineJoin = 'round';
// Top text font size
fontSize = canvas.width * topTextSize;
ctx.font = fontSize + 'px Impact';
ctx.lineWidth = fontSize / 20;
// Draw top text
ctx.textBaseline = 'top';
topText.split(' ').forEach(function (t, i) {
ctx.fillText(t, canvas.width / 2, i * fontSize, canvas.width);
ctx.strokeText(t, canvas.width / 2, i * fontSize, canvas.width);
});
// Bottom text font size
fontSize = canvas.width * bottomTextSize;
ctx.font = fontSize + 'px Impact';
ctx.lineWidth = fontSize / 20;
// Draw bottom text
ctx.textBaseline = 'bottom';
bottomText.split(' ').reverse().forEach(function (t, i) { // .reverse() because it's drawing the bottom text from the bottom up
ctx.fillText(t, canvas.width / 2, canvas.height - i * fontSize, canvas.width);
ctx.strokeText(t, canvas.width / 2, canvas.height - i * fontSize, canvas.width);
});
}
function init () {
// Initialize variables
topTextInput = document.getElementById('top-text');
bottomTextInput = document.getElementById('bottom-text');
topTextSizeInput = 0.10;
bottomTextSizeInput = 0.10;
imageInput = document.getElementById('image-input');
generateBtn = document.getElementById('generate-btn');
canvas = document.getElementById('meme-canvas');
ctx = canvas.getContext('2d');
canvas.width = canvas.height = 0;
// Default/Demo text
topTextInput.value = bottomTextInput.value = 'Demo\nText';
// Generate button click listener
generateBtn.addEventListener('click', function () {
// Read image as DataURL using the FileReader API
let reader = new FileReader();
reader.onload = function () {
let img = new Image;
img.src = reader.result;
generateMeme(img, topTextInput.value, bottomTextInput.value, topTextSizeInput, bottomTextSizeInput);
};
reader.readAsDataURL(imageInput.files[0]);
});
}
init();

HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Meme Generator</title>
<link rel="stylesheet" href="meme-generator.css">
</head>
<body>
<p>
<textarea id="top-text"></textarea>
</p>
<p>
<textarea id="bottom-text"></textarea>
</p>
<p>
<input type="file" id="image-input" accept="image/*">
</p>
<p>
<button id="generate-btn">Generate!</button>
</p>
<p>
<canvas id="meme-canvas" title="Right click -> "Save image as...""></canvas>
</p>
<script src="meme-generator.js"></script>
</body>
</html>
&#13;
非常感谢任何帮助!