admin管理员组文章数量:1333210
Why does the following code not produce three lines, all with similar gradients?
<html>
<body style="background: black;">
<canvas id="Test" width="516" height="404"> </canvas>
<script>
var ctx = document.getElementById('Test').getContext('2d');
ctx.lineWidth = 8;
function addColorStops(gradient) {
gradient.addColorStop(0.5, 'rgba(151, 165, 193, 0.5)');
gradient.addColorStop(1, 'rgba(151, 165, 193, 1)');
}
function drawLine(x1, x2, y) {
var g = ctx.createLinearGradient(x1, y, x2, y);
addColorStops(g);
ctx.strokeStyle = g;
ctx.moveTo(x1, y);
ctx.lineTo(x2, y);
ctx.stroke();
}
drawLine(10, 100, 10);
drawLine(10, 100, 30);
drawLine(10, 100, 50);
</script>
</body>
</html>
Instead the first line gets a very very slight gradient, the second line gets a pretty good gradient, and the last gets a drastic gradient.
I think this stems from misunderstanding of either how the parameters to createLinearGradient
are supposed to work, or misunderstanding how strokeStyle
assignments influence future strokes...
Why does the following code not produce three lines, all with similar gradients?
<html>
<body style="background: black;">
<canvas id="Test" width="516" height="404"> </canvas>
<script>
var ctx = document.getElementById('Test').getContext('2d');
ctx.lineWidth = 8;
function addColorStops(gradient) {
gradient.addColorStop(0.5, 'rgba(151, 165, 193, 0.5)');
gradient.addColorStop(1, 'rgba(151, 165, 193, 1)');
}
function drawLine(x1, x2, y) {
var g = ctx.createLinearGradient(x1, y, x2, y);
addColorStops(g);
ctx.strokeStyle = g;
ctx.moveTo(x1, y);
ctx.lineTo(x2, y);
ctx.stroke();
}
drawLine(10, 100, 10);
drawLine(10, 100, 30);
drawLine(10, 100, 50);
</script>
</body>
</html>
Instead the first line gets a very very slight gradient, the second line gets a pretty good gradient, and the last gets a drastic gradient.
I think this stems from misunderstanding of either how the parameters to createLinearGradient
are supposed to work, or misunderstanding how strokeStyle
assignments influence future strokes...
2 Answers
Reset to default 6Agh, I figured it out. I need to add a ctx.beginPath()
right before the ctx.strokeStyle = g;
. It turns out that lines are part of a path and thus if you don't begin a new path it'll think you're still continuing the old one, and thus use your original start point and final end point as the start and end for gradient purposes.
I was getting the strokeStyle overridden! By adding a beginPath my stroke colors work..
ctx.beginPath(); ctx.moveTo( x, y ); ctx.lineTo( x, y ); ctx.strokeStyle = "#182945"; ctx.stroke();
Thanks
本文标签: javascriptHTML5 Canvas gradients and strokeStyle have me confusedStack Overflow
版权声明:本文标题:javascript - HTML5 Canvas: gradients and strokeStyle have me confused - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742275320a2445085.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论