如何使用 canvas.toDataURL() 将 HTML Canvas 保存为图像?
htmlweb developmentfront end technology更新于 2025/8/18 10:20:17
使用 toDataURL() 方法获取画布的图像数据 URL。它将绘图(画布)转换为 64 位编码的 PNG URL。
示例
您可以尝试运行以下代码将画布保存为图像 −
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvasid = "newCanvas" width = "450" height = "300"></canvas>
<script>
var canvas = document.getElementById('newCanvas');
var ctx = canvas.getContext('2d');
// draw any shape
ctx.beginPath();
ctx.moveTo(120, 50);
ctx.bezierCurveTo(130,100, 130, 250, 330, 150);
ctx.bezierCurveTo(350,180, 320, 180, 240, 150);
ctx.bezierCurveTo(320,150, 420, 120, 390, 100);
ctx.bezierCurveTo(130,40, 370, 30, 240, 50);
ctx.bezierCurveTo(220,7, 350, 20, 150, 50);
ctx.bezierCurveTo(250,5, 150, 20, 170, 80);
ctx.closePath();
ctx.lineWidth = 3;
ctx.fillStyle ='#F1F1F1';
ctx.fill();
ctx.stroke();
var dataURL =canvas.toDataURL();
</script>
</body>
</html>
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

