pkirill
pkirill

Reputation: 41

HTLMCanvasElement internal dimension changes result in wrong change its layout

as I read before

The HTML element actually has two dimensions, the intrinsic dimensions (using the .width and .height properties you're modifying in JS) and the displayed dimensions (controlled in CSS with their width & height properties)

So I have a canvas which style defined as follows:

    let st = canvas.style;
    st.width = "100%";
    st.height = "100%";
    st.outline = "none";

And the problem is that when I change it's internal dimensions very strange animation happening and its shrinking. This animation is continues while the left scrollbar is visible on the page. Without visible scroll it does not happen. The problems only appears when I set scale to 125% for my display in the system and. Setting 100% in system and 125% in browser does not reproduce the problem.

This is the html

<!DOCTYPE html>
<html>
<head>
  <title>Canvas issue</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  <style>
    html, body { background-color: #2b2b2b; }
  </style>
</head>

<body>

<script type="module" charset="utf-8" src="example2.js"></script>

<button id="doit">Button1</button>
<button id="testme">Button2</button>

<div style="height: 50%" >
  <div style="height:100%; width: 50%; float:left">
    <div id="editor" style="width: 100%; height: 100%; position: relative">
    </div>
    <canvas
       width=100 height=100
       style="width: 100%; height: 100%; outline: none; cursor: text;"
    ></canvas>
  </div>
</div>

</body>
</html>

And this is the script:


    let container = document.getElementById("editor")

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

    let st = canvas.style;
    st.width = "100%";
    st.height = "100%";
    st.outline = "none";

    const observer = new ResizeObserver((entries) => {
        for (const entry of entries) {
            if (entry.target === canvas) {
                let size = entry.devicePixelContentBoxSize[0];
                console.log("w = " + size.inlineSize + ", h = " + size.blockSize);
                canvas.width = size.inlineSize;
                canvas.height = size.blockSize;
                context.fillStyle = "green";
                context.fillRect(0, 0, size.inlineSize, size.blockSize);
            }
        }
    });
    observer.observe(canvas, {box: "device-pixel-content-box"});
    container.appendChild(canvas)

The question is about the canvas that was created dynamically from the JS script (not the canvas initially in the HTML body)

I am expecting that changes to the canvas.width and canvas.height should not trigger any page re-layout.

Upvotes: 0

Views: 41

Answers (1)

pkirill
pkirill

Reputation: 41

The problem was with initial html page layout

Upvotes: 0

Related Questions