Skip to content
Advertisement

Moving canvas with translate() method

According to MDN documentation translate() method “moves the canvas and its origin” but the below code does not move the border of the canvas. If the translate() method moves the canvas shouldn’t the border move as well?

<!DOCTYPE html>

<head>
    <title>Temp</title>
    <style>
        canvas {
            border: 1px solid black;
        }

        body {
            margin: 0;
        }
    </style>
</head>

<body>
    <canvas id="myCanvas"></canvas>
    <script>
        const canvas = document.getElementById("myCanvas")
        canvas.width = 300;
        canvas.height = 300;

        const ctx = canvas.getContext("2d");
        ctx.translate(canvas.width / 2, canvas.height / 2);
    </script>
</body>

</html>

Advertisement

Answer

I don’t quite understand what you are trying to do. If you want to offset your canva, why not just do this?

document.getElementById("myCanvas").style.transform = "translate(50%, 50%)";
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement