ren*_*thy -1 javascript canvas download
我有画布元素(我使用 Fabric.JS)。在画布下方的屏幕上有 Dom textarea。
我有下载按钮,它可以工作 - 它将canvas元素下载为图像。但是,我还需要将文本中的textarea文本添加到此下载图像中。它应该在下面canvas。
这应该怎么做?我不知道如何实现这个技巧?
代码(它是 typescript 并在 React 应用程序中使用,但我猜在这里无关紧要,因为如果它是纯 Javascript 想法将是相同的 - 创建虚拟元素并触发点击)
const url = canvas.toDataURL({
format: "png",
width,
height,
});
const a = document.createElement("a");
a.href = url;
a.download = "download";
const clickHandler = () => {
setTimeout(() => {
URL.revokeObjectURL(url);
a.removeEventListener("click", clickHandler);
a.remove();
}, 150);
};
a.addEventListener("click", clickHandler, false);
a.click();
Run Code Online (Sandbox Code Playgroud)
您可以增加画布高度以在画布下方但画布内部留出空间。然后直接在画布内绘制文本,然后将其导出为图像。
这是一个您可以适应的示例:
var canvas = document.getElementById('canvas'),
text = document.getElementById('text'),
link = document.getElementById('link'),
ctx = canvas.getContext('2d');
canvas.width = "200";
canvas.height = "225"; // Make the height bigger that the main draw
// Draw something
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, 200, 200);
link.addEventListener("click", clickHandler, false);
function clickHandler () {
ctx.clearRect(0, 225, 200, 20); // Clear just the text part
ctx.font = "20px serif";
ctx.fillText(text.value, 0, 220);
var a = document.createElement("a");
a.download = 'filename.png';
a.href = canvas.toDataURL();
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
delete a;
}Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body {
width: 100px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<textarea id="text"></textarea>
<button id="link">Download</button>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
如果这是您要问的,请告诉我;)
编辑:这是这里的一个片段,它不会让您下载图像。您可以在本地运行它以查看它的工作情况。