这是一个奇怪的问题。我正在研究在画布中预渲染textarea以创建图像的能力。我从一篇很棒的文章开始,让我相信所有DOM元素都可以在画布中呈现。我只是略微调整了代码。本文可在以下网址找到:MDN (Mozilla Developer Network)
我已经调整了该代码示例以允许缩放svg和foriegnObject,以及更改“数据”字符串的创建方式。但是,它不会在画布中呈现,我的所有检查似乎都表明它应该。
我可能会说这个例子已经过时了,或者我的改动可能是问题,但我无法证明这一点。所以,我希望有人能够指出为什么他们的小提琴正常运行,但我的没有。
我试图直接链接到他们的小提琴,但它没有加载代码(至少在预览中)。您必须访问MDN链接才能访问它。
我的代码
var TC = {
canvas: null,
canvasContext: null,
textarea: null,
init: function () {
TC.canvas = document.getElementById('c');
TC.canvasContext = TC.canvas.getContext('2d');
TC.textarea = document.getElementById('t');
var data = TC.createSVGImg(500, 500);
document.getElementById('out').innerHTML = data;
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {
type: 'image/svg+xml;charset=utf-8'
});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
TC.canvasContext.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
},
createSVGImg: function (height, width) {
var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '"> [REPLACE] </svg>'
var fo = '<foreignObject height="' + height + 'px" width="' + width + 'px"> [REPLACE] </foreignObject>'
var d = '<div xmlns="http://www.w3.org/1999/xhtml"> [REPLACE] </div>'
d = d.replace('[REPLACE]', TC.textarea.outerHTML);
fo = fo.replace('[REPLACE]', d);
svg = svg.replace('[REPLACE]', fo);
return svg;
}
};
TC.init();
<div>
<canvas id="c" height="600" width="600" style="border:1px solid black"></canvas>
<textarea rows="3" cols="20" style="color:white; text-shadow:0 0 2px blue; overflow:hidden;" id="t">This is a test This is only a test</textarea>
<textarea id="out" rows="10" cols="80" style="overflow:hidden;"></textarea>
</div>
我希望有人可以发现我的失败,那个煽动可能会帮助其他有类似问题的人。感谢。
更新。我根据示例代码更改了对TC.createSVGImg的调用以包括高度和宽度,以防svg节点上不允许'%'。它没有影响结果。
答案 0 :(得分:0)
问题是你的svg无效。
将svg的输出复制粘贴到文件中,然后在google-chrome或firefox中打开,svg为空。
我手动编辑了你的svg以使其可渲染。 这就是你的svg应该是这样的:
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
<foreignObject width="500px" height="500px">
<div xmlns="http://www.w3.org/1999/xhtml">
<textarea rows="3" cols="20" style="color:white; text-shadow:0 0 2px blue; overflow:hidden;" id="t">This is a test This is only a test</textarea>
</div>
</foreignObject>
</svg>
希望这会有所帮助。我更改了svg属性值width和height以删除px。我还添加了一个带有xmlns的父div。我也运行你的javascript并在if (height && height.indexOf("px") < 0) { height += 'px'; }
上抛出异常,因为height作为int传递,而int没有方法indexOf(string do)。你可以使用大多数现代broswer的开发者界面在你的javascript中看到错误。 (f12 in chrome)