Reputation: 21
I am trying to display text on the screen and it's not working for me.
Here is some of my code you give you an idea on what I made:
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();
}
}
Upvotes: 0
Views: 448
Reputation: 21
The reason why it wasn't showing is that the text has the center point on the bottom left corner and not the top right corner. To fix this, I added t the y position the size of my text, in this case, 16px.
Upvotes: 1
Reputation: 4191
Change self
to this
inside your duck
class. In JavaScript, the global self
variable is a reference to the window
object, meaning it doesn't point to the instance of your class:
EDIT
You also have to update these parts:
get getWidth() {
return this.canvas.width; // added "this"
}
get getHeight() {
return this.canvas.height; // added "this"
}
Upvotes: 0