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