Search code examples
javascripthtmlcssbuttoncanvas

How to align canvas to center of button?


How would I center a canvas on a button?

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 150, 100);
<button>
  <canvas id="myCanvas" width="100" height="100"></canvas>. 
</button>


Solution

  • Your canvas is already centered. The rect is not centered because you're setting an offset of 20, 20. Try ctx.fillRect(0, 0, 100, 100);

    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 100, 100);
    <button>
      <canvas id="myCanvas" width="100" height="100"></canvas> 
    </button>