首页 > 解决方案 > 调整大小在保持绘制功能的同时适应父 div - 需要帮助

问题描述

import React, { useRef, useEffect, useState } from 'react';
import './app.css'

function App() {

  const canvasRef = useRef(null)
  const contextRef = useRef(null)
  const divRef = useRef(null)
  const [isDrawing, setIsDrawing] = useState(false)

  useEffect(() => {
    const canvas = canvasRef.current
    canvas.width = divRef.clientWidth * 2;
    canvas.height = divRef.clientHeight * 2;
    canvas.style.width = `${divRef.clientWidth}px`;
    canvas.style.height = `${divRef.clientHeight}px`;

    const context = canvas.getContext("2d")
    context.scale(2,2)
    context.lineCap = "round"
    //this line will provide the color - maybe change that to let users type in a color or click a color
    context.strokeStyle = "black"
    //here the line thickness is defined
    context.lineWidth = 5
    contextRef.current = context
  }, [])

  const startDrawing = ({nativeEvent}) => {
    const {offsetX, offsetY} = nativeEvent
    contextRef.current.beginPath()
    contextRef.current.moveTo(offsetX, offsetY)
    setIsDrawing(true)
  }

  const finishDrawing = () => {
    contextRef.current.closePath()
    setIsDrawing(false)
  }

  const draw = ({nativeEvent}) => {
    if(!isDrawing){
      return
    }
    const {offsetX, offsetY} = nativeEvent;
    contextRef.current.lineTo(offsetX, offsetY)
    contextRef.current.stroke()
  }

  return (
    <div id="canvasDiv" ref={divRef}>
      <canvas
        onMouseDown={startDrawing}
        onMouseUp={finishDrawing}
        onMouseMove={draw}
        ref={canvasRef}
      />
    </div>
  )
}

export default App
#canvasDiv {
    width: 500px;
    height: 500px;
    border-style: solid;
    border-width: 2px;
    border-color: black;
}

#canvasDiv canvas {
    width: 100%;
    height: 100%;
}

无法让我的绘图应用程序在父 div 的范围内工作。它确实可以调整画布的大小,但代价是绘图功能不再起作用。下面的代码是使用整个视图窗口作为画布工作时的外观,但我正在尝试将其实现为可移动窗口并且需要能够调整它的大小。

const canvas = canvasRef.current
canvas.width = window.innerWidth * 2;
canvas.height = window.innerHeight * 2;
canvas.style.width = `${window.innerWidth}px`;
canvas.style.height = `${window.innerHeight}px`;

标签: javascriptcssreactjscanvas

解决方案


推荐阅读