我正在尝试在屏幕上显示文本,但对我来说不起作用。
以下是我的一些代码,可让您对我的所作所为有所了解:
duck.js
class duck {
constructor (canvas, logs = false, start = () => {}, update = () => {}) {
document.documentElement.style.overflowX = 'hidden';
self.canvas = canvas;
self.ctx = self.canvas.getContext('2d');
self.logs = logs;
self.keys = {};
window.onkeyup = (e) => self.keys[e.keyCode] = false;
var dpi = window.devicePixelRatio;
var style_height = +getComputedStyle(self.canvas).getPropertyValue("height").slice(0, -2);
var style_width = +getComputedStyle(self.canvas).getPropertyValue("width").slice(0, -2);
self.canvas.setAttribute('height', style_height * dpi);
self.canvas.setAttribute('width', style_width * dpi);
self.init = () => {
var a;
self.logs ? console.info('Duck initialized!') : a = 0;
};
self.init.call();
start();
setInterval(update, 1);
};
rect (x = 0, y = 0, w = 1, h = 1, color = "#FFFFFF", fill = true) {
self.ctx.fillStyle = color;
fill ? self.ctx.fillRect(x, y, w, h): self.ctx.strokeRect(x, y, w, h);
}
fill (color = "#000000") {
self.ctx.fillStyle = color;
self.ctx.fillRect(0, 0, canvas.width, canvas.height);
}
text (x = 0, y = 0, text = 'Hello world!', align='left', font = '16px Verdana', color = '#000000') {
self.ctx.font = font;
console.log(self.ctx.font)
self.ctx.fillStyle = color;
console.log(self.ctx.fillStyle);
self.ctx.textAlign = align;
console.log(self.ctx.textAlign)
self.ctx.fillText(text, x, y);
}
get getWidth() {
return canvas.width;
}
get getHeight() {
return canvas.height;
}
screenshot() {
var image = self.canvas.toDataURL('image/png').replace("image/png", "image/octet-stream");
window.location.href = image;
}
keyDown(key = 'q') {
if (self.keys[key]) {return true} else {return false};
}
}
index.js
let duck_core = new duck(document.getElementById('main'), true, start, update);
function start() {
console.log('test');
}
function update() {
duck_core.fill('#FFFFFF');
duck_core.rect(0, 0, duck_core.getWidth, 10, '#222222');
duck_core.text(0, 0);
if (duck_core.keyDown('q')) {
duck_core.screenshot();
}
}
答案 0 :(得分:1)
之所以没有显示,是因为文本的中心点位于左下角而不是右上角。为了解决这个问题,我在y位置添加了文本大小,在本例中为16px。
答案 1 :(得分:0)
在您的self
类中将this
更改为duck
。在JavaScript中,全局self
变量是对window
对象的引用,这意味着它没有指向您的类的实例:
编辑
您还必须更新以下部分:
get getWidth() {
return this.canvas.width; // added "this"
}
get getHeight() {
return this.canvas.height; // added "this"
}