使用 html2canvas 下载 div 作为图像时添加标题

我有一个使用 html2canvas 下载一些 div 作为图像的函数。我还希望能够在保存图像时在图像顶部添加一个标题,即 chartColumnID。


  function saveAsImage(chartColumnID){

            html2canvas($('#'+ chartColumnID),

            {

                onrendered: function (canvas) {

                var a = document.createElement('a');

                    a.href = canvas.toDataURL("image/png");

                    a.download = chartColumnID;

                    a.click();

                }

             });

            };

我试过这样的东西,但它不起作用,没有标题出现。我将 a.text= 移动到不同的行以仔细检查我是否可能将它放在错误的位置但没有运气。


 function saveAsImage(chartColumnID){

            html2canvas($('#'+ chartColumnID),

            {

                onrendered: function (canvas) {

                var a = document.createElement('a');

                    a.href = canvas.toDataURL("image/png");

                    a.download = chartColumnID;

                    a.text= (15, 15, chartColumnID.replace(/([A-Z])/g, ' $1').trim());

                    a.click();

                }

             });

            };

有没有人知道如何使图表列 ID 也成为标题?


PIPIONE
浏览 104回答 1
1回答

桃花长相依

您可以尝试在画布上绘制文本(我没有检查过):function saveAsImage(chartColumnID) {&nbsp; html2canvas($('#' + chartColumnID), {&nbsp; &nbsp; onrendered: function(canvas) {// ----------------------------- here we draw text:&nbsp; &nbsp; &nbsp; const fontHeight = 14;&nbsp; &nbsp; &nbsp; const text = String(chartColumnID);&nbsp; &nbsp; &nbsp; const ctx = canvas.getContext("2d");&nbsp; &nbsp; &nbsp; ctx.font = fontHeight + "px Arial";&nbsp; &nbsp; &nbsp; ctx.textAlign = "left";&nbsp; &nbsp; &nbsp; ctx.fillStyle = "red"; // text color&nbsp; &nbsp; &nbsp; ctx.fillText(text, 0, fontHeight);// ------------------------------ your code as ususal:&nbsp; &nbsp; &nbsp; var a = document.createElement('a');&nbsp; &nbsp; &nbsp; a.href = canvas.toDataURL("image/png");&nbsp; &nbsp; &nbsp; a.download = chartColumnID;&nbsp; &nbsp; &nbsp; a.click();&nbsp; &nbsp; }&nbsp; });};它在画布上的外观示例:var canvas = document.getElementById("c");var chartColumnID = (Math.random() * 1000 + 1) | 0;canvas.width = 100;canvas.height = 100;const fontHeight = 14;const text = String(chartColumnID);const ctx = canvas.getContext("2d");ctx.font = fontHeight + "px Arial";ctx.textAlign = "left";ctx.fillStyle = "red"; // text colorctx.fillText(text, 0, fontHeight);canvas { border: 1px solid }<canvas id="c" />
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript