How to make a HTML5 canvas fit dynamic parent/flex box container

前端 未结 4 1080
死守一世寂寞
死守一世寂寞 2021-02-07 04:30

Is there a way I can create a canvas inside a dynamic re-sizing flex-box container?

Preferably a CSS only solution but I think JavaScript is required for redraw?

<
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 05:01

    Using object-fit provides a pure CSS solution. I think you need to check for yourself which value is better to set to object-fit between cover and contain, there are two examples below.

    $(document).ready(function() {
      var ctx = $("#stage")[0].getContext("2d");
      ctx.strokeStyle = "#FFFFFF";
      ctx.beginPath();
      ctx.arc(100, 100, 50, 0, 2 * Math.PI);
      ctx.stroke();
    });
    html,
    body {
      margin: 0;
      width: 100%;
      height: 100%;
    }
    
    body {
      display: flex;
      flex-direction: column;
    }
    
    header {
      width: 100%;
      height: 40px;
      background-color: red;
    }
    
    main {
      display: flex;
      flex: 1 1 auto;
      border: 1px solid blue;
      width: 80vw;
    }
    
    canvas {
      object-fit: cover;
      background-color: black;
      width: 100%;
      height: auto;
    }
    
    

    $(document).ready(function() {
      var ctx = $("#stage")[0].getContext("2d");
      ctx.strokeStyle = "#FFFFFF";
      ctx.beginPath();
      ctx.arc(100, 100, 50, 0, 2 * Math.PI);
      ctx.stroke();
    });
    html,
    body {
      margin: 0;
      width: 100%;
      height: 100%;
    }
    
    body {
      display: flex;
      flex-direction: column;
    }
    
    header {
      width: 100%;
      height: 40px;
      background-color: red;
    }
    
    main {
      display: flex;
      flex: 1 1 auto;
      border: 1px solid blue;
      width: 80vw;
    }
    
    canvas {
      object-fit: contain;
      background-color: black;
      width: 100%;
      height: auto;
    }
    
    

    You will also find both examples in JSFiddle https://jsfiddle.net/vfsgpm3q/, https://jsfiddle.net/vfsgpm3q/1/

提交回复
热议问题