【问题标题】:How can I set a different color for text and background of canvas HTML?如何为画布 HTML 的文本和背景设置不同的颜色?
【发布时间】:2020-09-02 16:29:12
【问题描述】:

我正在使用画布创建一个动态的命运之轮。每当我添加一个新项目时,它都会均匀地重新计算空间。我能够使用画布实现它。我知道canvas.fillStyle = somecolor; 将我想要的颜色设置为正在创建的切片。 我还想在每个切片中放置一些文本。 但是,我想不出办法让画布绘制与切片颜色不同颜色的文本。这可能吗?

这就是我正在做的事情

  const drawSlice = useCallback((deg: number, color: string, text:string) => {
    if (!canvasRef.current) {
        return;
      }
      const canvas: HTMLCanvasElement = canvasRef.current;
      const ctx = canvas.getContext("2d");

      const width = canvas.width;
      const center = width/2;
      const sliceDeg = 360 / wheelItems.length;

      if (ctx) {
        ctx.beginPath();
        ctx.fillStyle = color;
        ctx.fillText(text, center, deg2rad(deg));

        ctx.moveTo(center, center);
        ctx.arc(center, center, width / 2, deg2rad(deg), deg2rad(deg + sliceDeg));
        ctx.lineTo(center, center);
        ctx.fill();

      }
  },[wheelItems.length])

【问题讨论】:

    标签: javascript css reactjs canvas html5-canvas


    【解决方案1】:

    如果我正确理解您的问题,您可能希望在绘制文本和绘制切片之间更改 ctx.fillStyle

    if (ctx) {
        ctx.beginPath();
        ctx.fillStyle = color;
        ctx.fillText(text, center, deg2rad(deg));
    
        // here :
        ctx.fillStyle = color2;
        ctx.moveTo(center, center);
        ctx.arc(center, center, width / 2, deg2rad(deg), deg2rad(deg + sliceDeg));
        ctx.lineTo(center, center);
        ctx.fill();
    }
    

    您可以随时更改ctx.fillStyle,次数不限。

    【讨论】:

    • 成功了!谢谢!我注意到使用“fillText”的文字有点模糊,知道是什么原因造成的吗?
    • 如果你的文字模糊,可能是太小了;在调用fillText之前尝试使用ctx.font = "18px sans-serif";ctx.font = "bold 14px sans-serif";使用更大/更粗的字体。
    猜你喜欢
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2013-08-02
    • 2016-03-17
    • 2011-04-15
    • 2011-02-14
    • 1970-01-01
    • 2022-12-23
    相关资源
    最近更新 更多