Dom*_*nic 3 javascript html5 canvas
为什么以下代码不会产生三条线,所有线都具有相似的渐变?
<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>
Run Code Online (Sandbox Code Playgroud)
相反,第一行获得非常非常轻微的渐变,第二行获得非常好的渐变,最后一行得到一个剧烈的渐变.
我认为这源于对参数如何createLinearGradient工作的误解,或者误解了strokeStyle作业如何影响未来的笔画......
唉,我明白了.我需要在ctx.beginPath()之前添加一个权利ctx.strokeStyle = g;.事实证明,线条是路径的一部分,因此如果您没有开始新的路径,它会认为您仍在继续旧路径,因此使用您的原始起点和最终终点作为开始和结束用于渐变目的.