Tool address:
https://www.weiy.city/functions/static-meme-generator/
Use react state to record two variables:
function App() {
//...
const [textPosition, setTextPosition] = useState({ x: 0, y: 0 });
const handleDragStopped = (event, data) => {
setTextPosition( { x:data.x, y:data.y } );
console.log( textPosition );
};
// use it: textPosition.x, textPosition.y
}
Save image and text on it as a new image
Create a canvas and use it to draw image and text for a new image.
We need pay attention to text font weight and base line setting for the position effect.
const saveMeme = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = image;
const memeDiv = document.getElementById('memeDiv');
img.onload = () => {
const scaleRate = memeDiv.clientWidth / img.width;
console.log( "scaleRate: ", scaleRate, ", ", memeDiv.clientWidth, ", ", img.width );
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const actualFontSize = parseInt(fontSize/scaleRate);
ctx.font = `${fontWeight} ${actualFontSize}px Arial`; // set font weight at font part
console.log( "actualFontSize: ", actualFontSize, ", fontSize: ", fontSize );
ctx.fillStyle = color;
console.log( textPosition );
ctx.textBaseline = 'top'; // set text baseline at top, for set position correctly
ctx.fillText(text, textPosition.x/scaleRate, textPosition.y/scaleRate);
console.log( "text: ", text );
console.log( "after split: ", text.split('\n') );
const dataURL = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = dataURL;
link.download = 'meme.png';
link.click();
};
};
Draw the shadow outline of the text by canvas
const shadows = [
{offsetX: 1, offsetY: 1, color: 'black'},
{offsetX: -1, offsetY: -1, color: 'black'},
{offsetX: 1, offsetY: -1, color: 'black'},
{offsetX: -1, offsetY: 1, color: 'black'}
];
shadows.forEach(shadow => {
ctx.shadowOffsetX = shadow.offsetX;
ctx.shadowOffsetY = shadow.offsetY;
ctx.shadowBlur = 2;
ctx.shadowColor = shadow.color;
ctx.fillText(text, textPosition.x/scaleRate, textPosition.y/scaleRate);
});
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = 0;
// --------------- end ----------------
Make button more beautiful
.gradient-button {
background: linear-gradient(to right, #ff7e5f, #feb47b); /* Gradient background */
border: none; /* Remove borders */
color: white; /* White text */
padding: 15px 32px; /* Some padding */
text-align: center; /* Center the text */
text-decoration: none; /* Remove underline */
display: inline-block; /* Make the container inline-block */
font-size: 16px; /* Increase font size */
margin: 4px 2px; /* Some margin */
cursor: pointer; /* Pointer/hand icon */
border-radius: 8px; /* Rounded corners */
transition: transform 0.3s; /* Add a transition effect */
}
.gradient-button:hover {
transform: scale(1.05); /* Slightly enlarge button on hover */
}