I’m creating a game, i started with the menu, i tried to create a object class called button (also tried it with function), i made it with canvas context 2D, it works all fine, but when i run the code, the buttons created doesn’t center it with translate, it kinda of does when i use it with only one of them, but when i create more it doesnt go for the center. The script below for more context:
`class Button{ //maybe change this for a function, try with another html code and see if it works
// Define the button properties that we will call to create a especified one.
constructor(color, textColor, name, x, y, width, height, fontSize){
const textWidth = context.measureText(name).width //Define a especial variable of the text width that will debug in console.log
// Define all button properties in constructor.
this.color = color
this.textColor = textColor
this.name = name
this.x = x
this.y = y
this.width = width
this.height = height
this.fontSize = fontSize
let translateX = width/2
let translateY = height/2
//Define the button Style
context.translate(translateX, translateY)
context.fillStyle = color
context.fillRect(x,y,width,height)
//Define how the button text will be draw, (just put nothing at the creation of especified and it will not have a text on it.)
context.fillStyle = textColor
context.font = "bold 14px arial"
context.translate(width/2 - 14 ,height/2)
context.fillText(name,x,y, fontSize)
//Debug
console.log("The > " + "!" + name + "!" + " width is " + textWidth)
console.log("The > " + "color of " + name + " is: " + color)
console.log("The > " + "text color of " + name + " is: " + textColor)
console.log("The > " + "position X of " + name + " is: " + x)
console.log("The > " + "position Y of " + name + " is: " + y)
console.log("The > " + "width of " + name + " is: " + width)
console.log("The > " + "height of " + name + " is: " + height)
console.log("The > " + "font size of " + name + " is: " + fontSize)
console.log("The > " + "translate X of " + name + " is: " + translateX)
console.log("The > " + "translate Y of " + name + " is: " + translateY)
}
}
function draw(){
scene = level[0]
context.fillStyle = "gray"
context.fillRect(0,0,500,500)
if(scene == level[0]){
const start = new Button("white","black","start",500/2, 100, 100, 30, 30)
const start0 = new Button("white","black","start1",500/2, 100, 100, 30, 30)
const testZero = new Button("white","black","",500/2, 100, 100, 30, 30)
}
}`
Thats the code, when i run it in my browser, it looks like this:
Here
Although the buttons have the same x and y, they change its x by little, and i dont know what it is. If you know, please tell me, i will be greatful 🙂
I expected it to go for the center of its origin, and simply go for the center with only (500/2), but it won’t.