Search code examples
javascriptcanvasquadratic-curve

How come this doesnt draw rounded corners?


I am trying to draw a rectangle with rounded corners, so far only the top corners are rounded, But the bottom two corners are not somehow? Full code: https://github.com/GunZi200/Memory-Colour/blob/master/SourceCode.js

Can you guys spot the error?

        ctx.fillStyle = rectangle.color;
        ctx.moveTo((rectangle.x + 40 - 30) * Xf, (rectangle.y + 30 - 30) * Yf);
        ctx.lineTo((rectangle.x + 40 + 40) * Xf, (rectangle.y + 30 - 30) * Yf);
        ctx.quadraticCurveTo((rectangle.x + 60 + 30) * Xf, (rectangle.y + 30 - 30) * Yf, (rectangle.x + 60 + 30) * Xf, (rectangle.y + 50 - 40) * Yf);
        ctx.lineTo((rectangle.x + 60 + 30) * Xf, (rectangle.y + 60 + 30) * Yf);
        ctx.quadraticCurveTo((rectangle.x + 60 + 30) * Xf, (rectangle.y + 80 + 30) * Yf, (rectangle.x + 50 + 40) * Xf, (rectangle.y + 80 + 30) * Yf);
        ctx.lineTo((rectangle.x + 40 - 40) * Xf, (rectangle.y + 80 + 30) * Yf);
        ctx.quadraticCurveTo((rectangle.x + 30 - 30) * Xf, (rectangle.y + 80 + 30) * Yf, (rectangle.x + 30 - 30) * Xf, (rectangle.y + 70 + 40) * Yf);
        ctx.lineTo((rectangle.x + 30 - 30) * Xf, (rectangle.y + 50 - 40) * Yf);
        ctx.quadraticCurveTo((rectangle.x + 30 - 30) * Xf, (rectangle.y + 30 - 30) * Yf, (rectangle.x + 50 - 40) * Xf, (rectangle.y + 30 - 30) * Yf);

Example of code above


Solution

  • I didn't check your code, but here is a generic function to draw a rounded rectangle:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    var x=50;
    var y=50;
    var w=50;
    var h=35;
    var direction=1;
    ctx.strokeStyle='gray';
    ctx.fillStyle='orchid';
    ctx.lineWidth=5;
    
    animate();
    
    function animate(){
      requestAnimationFrame(animate);
    
      ctx.clearRect(0,0,cw,ch);
      roundRect(x,y,w,h,10);
      ctx.stroke();
      ctx.fill();
    
      w+=direction;
      h+=direction;
      if(w<50 || w>100){
        direction*=-1;
        w+=direction;
        h+=direction;        
      }
    
    }
    
    function roundRect(x,y,width,height,radius) {
      ctx.beginPath();
      ctx.moveTo(x + radius, y);
      ctx.lineTo(x + width - radius, y);
      ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
      ctx.lineTo(x + width, y + height - radius);
      ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
      ctx.lineTo(x + radius, y + height);
      ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
      ctx.lineTo(x, y + radius);
      ctx.quadraticCurveTo(x, y, x + radius, y);
      ctx.closePath();
    }
    body{ background-color: ivory; padding:10px; }
    #canvas{border:1px solid red;}
    <canvas id="canvas" width=300 height=300></canvas>