Home > Net >  How to center the "fillRect" -methode relative to canvas element
How to center the "fillRect" -methode relative to canvas element

Time:09-30

I want to center the blue rectangle made with fillrec relative to the size of the canvas (aqua). I didnt find a solution yet, due to my newbie knowledge working with JS. And my little research and trying things out didn't help either. I was hoping for a little guidance regarding that matter.

canvas {
    padding: 0;
    margin: auto;
    display: block;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: aqua;
}
<html> 
    <link rel="stylesheet" href="canvas.css">
    <body>
        <canvas width="800", height="800", id="1"   > </canvas>
        <script>

            let canvas = document.querySelector('canvas');
            let context = canvas.getContext('2d');

            context.fillStyle = "Blue"
            context.fillRect(15, 15, 400, 400);

        </script>
    </body>
</html>

CodePudding user response:

Uhhh if you canvas is always 800 and that square always 400 you can do

context.fillRect(200, 200, 400, 400);

It just plus and minus Or you can check this out How do I center a rectangle on a canvas

  • Related