gpt4 book ai didi

javascript - 通过 JavaScript 函数将文本写入 Canvas

转载 作者:行者123 更新时间:2023-11-30 09:17:48 27 4
gpt4 key购买 nike

我了解如何在函数外部用 JavaScript 将文本放到 Canvas 上,但是将代码放在函数中似乎会破坏一切

示例:

var c = document.getElementById("APICanvas");
var canvas = c.getContext("2d");
canvas.font('20px Times New Roman);
canvas.fillText("Hello, world!", 20, 20);

这会导致 "Hello, world!"canvas 上的 (20,20),但是

function text(text,x,y) {
var c = document.getElementById("APICanvas");
var canvas = c.getContext("2d");
canvas.font('20px Times New Roman);
canvas.fillText(text,x,y);
}

text("Hello, world!",20,20);

这会导致 canvas 上没有显示任何内容。

我不知道为什么在函数内部使用 this 不起作用,我很困惑。

最佳答案

font 是一个属性,不是函数。您必须使用赋值运算符设置属性。您还错过了属性字符串值末尾的结束 '

改变

canvas.font('20px Times New Roman);

canvas.font = '20px Times New Roman';

function text(text,x,y) {
var c = document.getElementById("APICanvas");
var canvas = c.getContext("2d");
canvas.font = '20px Times New Roman';
canvas.fillText(text,x,y);
}

text("Hello, world!",20,20);
<canvas id="APICanvas"></div>

关于javascript - 通过 JavaScript 函数将文本写入 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53863258/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com