【问题标题】:Javascript, canvas fillstyle doesn't consistently change colorJavascript,画布填充样式不会始终如一地改变颜色
【发布时间】:2020-10-19 23:02:38
【问题描述】:

这是一个更大的代码的一部分,但由于某种原因,我无法控制绘制弧线的颜色。当我创建圆弧然后调用绘图函数时,圆弧出现但它被填充为黑色。 (不是预期的蓝色)

    class calnote {
    constructor() {
        this.radius = calnoteradius;
        this.positionx = Math.floor(Math.random() * 700);
        this.positiony = Math.floor(Math.random() * 500);

    }
    change_position() {
        this.positionx = Math.floor(Math.random() * 700);
        this.positiony = Math.floor(Math.random() * 500);
        
    }
    draw(ctx) {
        
        ctx.beginPath();
        ctx.arc(this.positionx, this.positiony, this.radius,0, 2 * Math.PI);
        ctx.fillstyle = "#0000FF";
        ctx.fill();
        ctx.closePath();
    }
}

不过后来我调用了这个函数

function drawScore() {
        ctx.beginPath();
        ctx.font = "16px Arial";
        ctx.fillStyle = "#FF0000";
        ctx.fillText("Combo: "+ combo, 8, 40);
        ctx.fillText("Score: "+ score, 8, 20);
        ctx.closePath();
    }

现在分数用红色书写,弧线在绘制时用红色填充。 (如果我改变这个颜色,它会改变分数和所有后来的弧线,所以我可以让它们变成蓝色、绿色等)。

最后,我知道绘图功能正在更新,因为:

  1. 当 x 和 y 位置发生变化时,圆弧的位置会相应更新
  2. 当我调用 console.log(ctx.fillstyle) 时,记录的十六进制值会发生适当的变化(因此在这种情况下它将记录 #0000FF),即使显示的弧线是红色的
  3. 在我的区间循环中,我确实调用了 ctx.clearRect(0,0,canvas.width, canvas.height);因此位置会适当更新。

如果有人有任何想法,请告诉我。

【问题讨论】:

    标签: javascript canvas colors


    【解决方案1】:

    您的ctx.fillstyle = "#0000FF"; 似乎只是一个错字,S 应该是大写

    class calnote {
      constructor() {
        this.positionx = Math.floor(Math.random() * 100);
        this.positiony = Math.floor(Math.random() * 100);
      }
    
      change_position() {
        this.positionx = Math.floor(Math.random() * 100);
        this.positiony = Math.floor(Math.random() * 100);
      }
    
      draw(ctx) {
        ctx.beginPath();    
        ctx.arc(this.positionx, this.positiony, 10, 0, 2 * Math.PI);
        ctx.fillStyle = "#0000FF";
        ctx.fill();    
      }
    }
    
    function drawScore() {
      ctx.beginPath();
      ctx.font = "16px Arial";
      ctx.fillStyle = "#FF0000";
      ctx.fillText("Combo: ", 8, 40);
      ctx.fillText("Score: ", 8, 20);
    }
    
    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      drawScore()
      note.change_position()
      note.draw(ctx)    
    }
    
    var canvas = document.getElementById('c');
    var ctx = canvas.getContext('2d');
    note = new calnote()
    
    setInterval(draw, 200);
    <canvas height="160" width="300" id="c"></canvas>

    【讨论】:

    • 谢谢!如此愚蠢的小错误,我在兔子洞里走得太远了,无法修复!
    猜你喜欢
    • 2012-01-22
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    相关资源
    最近更新 更多