【问题标题】:Canvas only drawing in top left quadrant仅在左上象限中绘制的画布
【发布时间】: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


    【解决方案1】:

    您正在访问画布元素的 offsetHeight 和宽度,这是画布占用的空间而不是画布的大小。您应该根据画布的宽度和高度进行随机计算。将 maxWidth 和 height 更改为以下值将使您的数字基于画布尺寸而不是 DOM 中画布元素的尺寸。

    const maxWidth = canvas.width;
    const maxHeight = canvas.height;
    

    【讨论】:

    • 非常感谢您的帮助。从我想要使用尺寸而不是显示尺寸的描述中可以意识到这一点。但后来我使用显示大小进行计算。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-01-11
    • 2016-04-29
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多