【发布时间】:2020-12-23 03:42:21
【问题描述】:
尝试为简单的浏览器游戏创建空间背景时,我们遇到了仅在左上象限绘制画布的问题。
这是一个在 JS 中使用 Emotion 作为 CSS 的 React 应用程序。我们正在尝试通过其宽度和高度属性设置画布尺寸,以依靠它进行绘画。然后我们想使用通过情感注入的 CSS 来调整画布的大小以适应其容器宽度,同时保持纵横比。
代码沙箱可以在https://codesandbox.io/s/epic-liskov-degs9找到
有问题的组件如下所示:
/** @jsx jsx */
import { css, jsx } from "@emotion/core";
import { useEffect } from "react";
import { useRef } from "react";
// Inspired by: https://codepen.io/dudleystorey/pen/QjaXKJ
const Starfield = () => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const drawStars = () => {
function getRandom(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const canvas = canvasRef.current as HTMLCanvasElement;
if (!canvas) return;
const context = canvas.getContext("2d");
if (!context) return;
const stars = 600;
const colorrange = [0, 60, 240];
const maxWidth = canvas.offsetWidth;
const maxHeight = canvas.offsetHeight;
for (var i = 0; i < stars; i++) {
const x = Math.random() * maxWidth;
const y = Math.random() * maxHeight;
/**
* x and y are what we expect but stars only show up
* in the top left corner ????
*/
console.log(x, y);
const radius = Math.random() * 1.2;
const hue = colorrange[getRandom(0, colorrange.length - 1)];
const sat = getRandom(50, 100);
context.beginPath();
context.arc(x, y, radius, 0, 360);
context.fillStyle = "hsl(" + hue + ", " + sat + "%, 88%)";
context.fill();
}
};
useEffect(() => {
drawStars();
}, []);
return (
<canvas
width="1500"
height="1000"
css={css`
background: #111;
width: 100%;
height: auto;
`}
ref={canvasRef}
></canvas>
);
};
export default Starfield;
【问题讨论】:
标签: css reactjs html5-canvas emotion