Html HTML5 Canvas 绘制多色线条
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3594653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 Canvas drawing multicolored lines
提问by Amarsh
I am trying to draw two parallel lines on the canvas, but it seems like properties of the latter overwrites the former. Please suggest what could be wrong :
我试图在画布上绘制两条平行线,但后者的属性似乎覆盖了前者。请提出什么可能是错误的:
<html>
<head>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// draw a 10 pix green line
ctx.strokeStyle='#00cc00';
ctx.lineWidth=10;
ctx.moveTo(100,0);
ctx.lineTo(100,1000);
ctx.stroke();
// draw a 20 pix red line
ctx.strokeStyle='#cc0000';
ctx.lineWidth=20;
ctx.moveTo(140,0);
ctx.lineTo(140,1000);
ctx.stroke();
}
</script>
</head>
<body onload="draw()">
<div><canvas id="canvas" width="1000" height="1000"></canvas></div>
</body>
</html>
回答by Matti Virkkunen
Call ctx.beginPath
before drawing each line. When the strong stroke
call is made, the first line is still part of the current path so it gets drawn again in the new color.
ctx.beginPath
在绘制每条线之前调用。当进行强调stroke
用时,第一行仍然是当前路径的一部分,因此它会再次以新颜色绘制。