【发布时间】:2020-03-22 00:08:07
【问题描述】:
关于这个问题的更详细背景是here,我试图查看该线程中链接的答案,这就是我卡住的地方。
A 已经创建了一个 PHP 文件,该文件通过另一个线程中显示的 ajax 调用在另一个 PHP 文件中的 div 元素内通过 ajax 加载。 PHP文件使用数据库拉取和带有chart.js的html来制作图表画布,我想将其保存为服务器上的图像。
下面是我正在尝试做的代码示例。
// html stuff to make a html canvas is above here.
// PHP stuff to take post data, get data from database and insert it into barChartData and chartOptions vars is above here. (these two vars contain all the chart.js config stuff and the chart works.)
var ctx = document.getElementById("Cloudbar1").getContext("2d");
Chart.defaults.global.defaultFontColor = 'black';
Chart.defaults.global.defaultFontFamily = "Arial, sans-serif";
Chart.defaults.global.defaultFontSize = 16;
window.myBar = new Chart(ctx, {
type: "bar",
data: barChartData,
options: chartOptions
});
//convert canvas element to a url format.
var dataURL = ctx.toDataURL();
//now send the file to the server with yet another ajax call.
$.ajax({
type: "POST",
url: "savecanvasimgtoserver.php",
data: {
imgBase64: dataURL
}
})
尝试运行时,我收到控制台错误提示
"Uncaught TypeError: ctx.toDataURL is not a function"
我认为这并不重要,因为我还没有在上述错误的代码中得到这么多,但是上面代码指向的 php 文件只包含:
$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$fileName = 'chart.png';
file_put_contents($fileName, $fileData);
取自this问题。
据我所知,当你得到一个“x 不是函数”而它是一个函数时,这意味着你试图放入函数中的东西在某种程度上是无效的,但“ctx”无疑是画布元素并在这种情况下有效。
【问题讨论】:
-
如果你把 ctx.toDataURL();进入数据 imgBase64 属性而不是变量。我怀疑图表还没有准备好(加载、创建)。
-
它应该是画布而不是上下文不应该吗? developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/…
-
@cptnk 带着这种怀疑,我尝试在 8 秒超时内将 ajax 调用封装到 savecanvasimagetoserver.php 中。 (没有改变)然后做你的建议,但我以前从来没有这样做过,所以不确定语法,我尝试将它作为“数据:{ imgBase64:ctx.toDataURL()”} 但这给出了完全相同的错误. (我确实记得注释掉上面的转换行!)
-
哦,我差点忘记了,有一件东西我应该扔进去,以防万一。所有这些的输出(我使图表显示在通过 jquery show() 弹出的隐藏 div 中)并且在运行此处讨论的代码时,该 div 仍然隐藏在 display:none; 的内联 css 中。 .这会阻止我使用此画布 todataURL() 功能吗?
标签: javascript php jquery html ajax