0: 半成品展示:- canvas绘制地铁路线图
1
0.3
0.7
1: canvas的大小。
canvas的大小由其width,height属性确定,千万别通过css设置其width,height大小。
1.1 勿通过css设置canvas的大小
css设置的canvas这个元素DOM的大小,并非canvas画布的大小。如果DOM大小和画布大小不一样,那么绘制的内容就会变形。
1.1.1 采用默认画布大小绘制:fillRect(20, 20, 50, 50)
1.1.2 采用默认画布大小,并通过css设置canvas元素大小。
canvas {
width: 600px;
height: 100px;
}
复制代码
1.2 设置canvas大小的正确方式
// App.tsx
function App() {
const canvasContainerRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
if (canvasContainerRef.current === null || canvasRef.current === null) {
return;
}
const { clientWidth, clientHeight } = canvasContainerRef.current;
canvasRef.current.width = clientWidth;
canvasRef.current.height = clientHeight;
}, []);
return (
<div className="app-container-view">
<div className="canvas-container-view">
<div className="canvas-view" ref={canvasContainerRef}>
<canvas ref={canvasRef}></canvas>
</div>
</div>
</div>
);
}
// App.scss
.app-container-view {
width: 100%;
height: 100%;
background-color: #ededed;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
.canvas-container-view {
width: 87%;
height: 87%;
border-radius: 12px;
padding: 12px;
background-color: white;
.canvas-view {
width: 100%;
height: 100%;
}
}
}
2: canvas模糊问题
context.scale(window.devicePixelRatio, window.devicePixelRatio);