javascript - 调整大小
问题描述
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`;
解决方案
推荐阅读
- javascript - 如何从Javascript中的内部函数调用外部类函数?
- javascript - JavaScript 新的承诺请求
- android - Android:不同语言的测验应用程序 - 无法从字符串数组中获取问题
- c - 读写 .code/.text 段有什么用?
- java - 我想检索 Google 日历的活动、提醒和目标信息
- ios - 如何接收 json 字符串并将其转换为字典?
- reactjs - 状态变量显示值“未定义”,但已设置默认值“假”
- azureservicebus - WebJobs 和服务总线触发函数 - 性能注意事项
- swift - 如何处理失败的可选绑定
- python - 在默认 Django 表单中添加单选按钮: