在 MDN 文档和 SO 之前的问题中,没有提及完全(合理)对齐。
有人遇到同样的问题并且已经解决了吗?
PS:之前有与此主题相关的问题,但没有正确/可接受的答案。
示例:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var img = new Image();
img.onload = function () {
context.drawImage(img, 0, 0);
context.font = "18px sans-serif";
context.textAlign = "full"; //the question: this option doesn't exist
context.fillText("The Text", 50, 50);
};
img.src = imagePath; //note: change it with real image URL or image URI
最后我使用 https://github.com/tsayen/dom-to-image 来解决这个问题。我只需要在 HTML 和 CSS 中“绘制”所有内容,然后将其转换为图像。
示例(来自他们的网站,我使用它进行了一些适当的编辑):
var node = document.getElementById('my-node');
domtoimage.toPng(node)
.then(function (dataUrl) {
var img = new Image();
img.src = dataUrl;
document.body.appendChild(img);
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});