【问题标题】:HTML5 Gradient: changing color of gradient changes color of triangle on a canvasHTML5渐变:改变渐变的颜色会改变画布上三角形的颜色
【发布时间】:2016-10-22 14:38:27
【问题描述】:

我正在接受一个非常棒的HTML5 Tutorial。我到了视频画布部分的径向渐变部分,大约是 59 分 44 秒。我遇到了一个问题,当我在径向渐变中更改渐变颜色时,我无法确定在哪里,它为三角形添加填充。 click here for a screenshot of the output.

画布的代码在一个JS文件中,这里是函数sn-p,带有三角形和径向渐变:

function init(){
    var canvas = document.getElementById("canvas");

    if(canvas.getContext){
        var ctx = canvas.getContext("2d");
        // rectangles
        ctx.fillStyle = "#FAEBD7";
        ctx.fillRect(0,0,canvas.width,canvas.height);

        // triangle
        ctx.fillStyle = "yellow";
        ctx.beginPath();
        ctx.moveTo(350,200);
        ctx.lineTo(400,50);
        ctx.lineTo(450,200);
        ctx.closePath();
        ctx.fill();

        // add stroke to triangle
        ctx.strokeStyle = "green";
        ctx.beginPath();
        ctx.moveTo(350,200);
        ctx.lineTo(400,50);
        ctx.lineTo(450,200);
        ctx.closePath();
        ctx.stroke();

        // radial gradient
        var radGrad = ctx.createRadialGradient(275,250,5,290,260,100);
        radGrad.addColorStop(0,"red");
        radGrad.addColorStop(1,"pink");
        ctx.fillStyle=radGrad;
        ctx.arc(250,200,25,0,Math.PI*2,true);
        ctx.fill(); 
    }
}

onload = init;

当我移除径向渐变时,三角形会恢复到原来的样子。 here is a screenshot or the correct looking triangle.

我尝试弄乱var radGrad = ctx.createRadialGradient(275,250,5,290,260,100)的参数,寻找可能匹配的数字并改变它们,寻找与径向渐变和三角形的冲突,但没有成功。

谢谢!

请帮助我,以便我可以在页面上设置径向渐变和正确的三角形。

【问题讨论】:

  • 我在这里做了一些更改与您的渐变定位有关,jsfiddle.net/1gfxyz0m 但是我有点不确定您在问什么,如果它是渐变的位置,它应该是最上面的效果.这也值得一读:developer.mozilla.org/en-US/docs/Web/API/…
  • @JonathanNewton 在我发布的屏幕截图中,它显示三角形的样式与圆形不同。圆应该有自己的渐变。无论我对圆圈做什么,三角形都会获得其中一种颜色。我不明白为什么。即使是三角形的 fillStyle 也是“黄色”,但它仍然与圆形完全相同。

标签: javascript html canvas


【解决方案1】:

我查看了他的三角形和arc,区别在于ctx.beginPath();ctx.closePath();,它阻止了我的第二个radGrad.addColorStop(1,"pink") 或我添加的任何颜色,无法更改三角形的颜色。您可以在下面看到新代码和screenshot here

    var radGrad = ctx.createRadialGradient(275,250,5,290,260,100);
    radGrad.addColorStop(0,"red");
    radGrad.addColorStop(1,"pink");
    ctx.fillStyle=radGrad;
    ctx.beginPath();
    ctx.arc(250,200,25,0,Math.PI*2,true);
    ctx.closePath();
    ctx.fill(); 

【讨论】:

  • closePath 对你弧度没用
  • @Kaiido 是的,但它解决了我遇到的问题。
  • 不是 beginPath 做的,closePath 在这里没用。
  • @Kaiido 好的,谢谢。我明白了,beginPath() 开始了新路径,没有它,我仍在编辑以前的图形。对吗?
  • 是的,就是这样。 closePath() 只是一个 lineTo(first_declared_point_of_the_path_or_last_moved_point)
猜你喜欢
  • 2018-01-21
  • 1970-01-01
  • 2010-12-17
  • 2012-08-25
  • 2020-11-27
  • 2020-11-24
  • 1970-01-01
相关资源
最近更新 更多