【问题标题】:Canvas doesn't fill up completely画布没有完全填满
【发布时间】:2020-03-11 04:35:22
【问题描述】:

我在 ReactJs 中使用了一个画布,当我想绘制一个占据整个画布的矩形时,它并没有完全填满,它在画布的长度和宽度上留下了一点空间。

我强调我正在通过 css 更改画布的宽度和高度,所以我使用 canvas.client 属性

我怎样才能让它完全充满?

我的代码:

const PDFDocumentWrapper = styled.div`
  canvas {
    width: 100% !important;
    height: auto !important;
  }
`;
 <PDFDocumentWrapper>
     <canvas ref={canvasRef}
        onMouseDown={
          e => {
                let nativeEvent = e.nativeEvent;
                 const canvas = canvasRef.current
                 const ctx = canvas.getContext('2d')
                 handleMouseDown(nativeEvent, ctx);
                }}/>
 </PDFDocumentWrapper>

我的功能:

function handleMouseDown(event, ctx) {
    ctx.fillStyle="#f00";
    ctx.fillRect(0,0,ctx.canvas.clientWidth,ctx.canvas.clientHeight);

    }

注意: 如果我使用 ctx.width 它返回 undefined

【问题讨论】:

    标签: html reactjs canvas


    【解决方案1】:

    你试过了吗:

    function handleMouseDown(event, ctx) {
        ctx.fillStyle="#f00";
        ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
    }
    

    我认为由于浏览器的缩放,clientHeight/clientWidth 和 height/width 之间可能存在差异。

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      相关资源
      最近更新 更多