Home > Enterprise >  Border-radius on canvas elements
Border-radius on canvas elements

Time:09-14

I'm creating a little game based on this code: https://www.w3schools.com/graphics/tryit.asp?filename=trygame_default_gravity

everything ok, but I would like to put the border-radius on green stakes, does anyone have any ideas? the part that creates the components is this:

 function component(width, height, color, x, y, type) {
     this.type = type;
     this.score = 0;
     this.width = width;
     this.height = height;
     this.speedX = 0;
     this.speedY = 0;    
     this.x = x;
     this.y = y;
     this.gravity = 0;
     this.gravitySpeed = 0;
     this.update = function() {
      ctx = myGameArea.context;
      if (this.type == "text") {
        ctx.font = this.width   " "   this.height;
        ctx.fillStyle = color;
        ctx.fillText(this.text, this.x, this.y);
      } else {
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
      }
    }
this.newPos = function() {
    this.gravitySpeed  = this.gravity;
    this.x  = this.speedX;
    this.y  = this.speedY   this.gravitySpeed;
    this.hitBottom();
}
this.hitBottom = function() {
    var rockbottom = myGameArea.canvas.height - this.height;
    if (this.y > rockbottom) {
        this.y = rockbottom;
        this.gravitySpeed = 0;
    }
}
this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x   (this.width);
    var mytop = this.y;
    var mybottom = this.y   (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x   (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y   (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
        crash = false;
    }
    return crash;
}

}

While the part where he creates the green stakes is this:

 if (myGameArea.frameNo == 1 || everyinterval(150)) {
    x = myGameArea.canvas.width;
    minHeight = 20;
    maxHeight = 200;
    height = Math.floor(Math.random()*(maxHeight-minHeight 1) minHeight);
    minGap = 50;
    maxGap = 200;
    gap = Math.floor(Math.random()*(maxGap-minGap 1) minGap);
    myObstacles.push(new component(10, height, "green", x, 0));
    myObstacles.push(new component(10, x - height - gap, "green", x, height   gap));
}

CodePudding user response:

The components you draw on the <canvas> are not html elements, therefore you cant style them with CSS.

What you want is to replace your fillRect() function with a function that can draw rectangles with rounded corners.

One such function is provided as an answer to this stackoverflow question: How to draw a rounded rectangle using HTML Canvas?

  • Related