首页 > 解决方案 > 当它应该是纯色时,html5画布strokeStyle褪色问题

问题描述

我正在处理一些我不熟悉的代码,并试图解决一个奇怪的错误。本质上,画布有不同的部分,目标是计算已填充部分的百分比。有两种不同的颜色(红色和黄色,具有特定的 RGB 和 Hex 值)可用于在该部分中绘制一条线,就像画笔描边一样使用。当我以单一颜色绘制整个部分时,部分填充的百分比正确显示为 100%。但是,如果我返回并在该部分中绘制一条其他颜色的线,则少数像素不是特定的 RGB 值,因此 % 变为 99%。当我使用图像查看器并放大图像时,我可以看到大部分绘制的线条都很好,但外边缘是渐变的,会淡入另一种颜色。

剖面图

像素化图像边界

这是用于在画布上绘制的代码:

handleMouseMove() {
    const canvas = this.props.canvasInfo;
    const context = canvas.getContext('2d');

    if (!(this.props.canvasObject && context && this.image)) {
      setCanvasError(this.props.dispatch, Constants.CANVAS_GENERIC_ERROR);
      return;
    }
    const { isDrawing, mode, brushSize, brushColor } = this.props.canvasObject;

    if (isDrawing && mode && brushSize && brushColor) {
      context.strokeStyle = brushColor;
      context.lineJoin = 'round';
      context.lineWidth = brushSize;
      context.globalCompositeOperation = 'source-over';
      if (mode === Constants.ERASER_MODE) {
        context.strokeStyle = Constants.CANVAS_BACKGROUND_COLOR;
      }
      context.beginPath();

      const localPos = {
        x: this.lastPointerPosition.x - this.image.x(),
        y: this.lastPointerPosition.y - this.image.y(),
      };
      context.moveTo(localPos.x, localPos.y);

      const stage = this.image.getStage();
      const pos = stage.getPointerPosition();
      localPos.x = pos.x - this.image.x();
      localPos.y = pos.y - this.image.y();

      context.lineTo(localPos.x, localPos.y);
      context.closePath();
      context.stroke();
      this.lastPointerPosition = pos;
      this.image.getLayer().draw();
    }

我不确定为什么像素不只是两种指定颜色中的任何一种。我在html 5 canvas LineTo() 线条颜色问题上看到这可能是抗锯齿,但我不知道如何解决它。

标签: javascriptcanvashtml5-canvas

解决方案


推荐阅读