绘制部分无描边的路径,部分有描边的路径

Draw part of path without stroke, part with stroke

本文关键字:路径 绘制部      更新时间:2023-09-26

我正在使用canvas元素和JavaScript绘制路径

路径有填充和描边。然而,我只想将描边应用于路径的一部分。

我已经创建了一个JSFiddle,它显示了我一直在绘制的形状,并附有注释,解释哪些部分应该或不应该描边。

http://jsfiddle.net/DanielApt/22973/

如何使部分路径没有描边?

我一直在使用:

function draw() 
{  
    var canvas = document.getElementById("canvas");  
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = 'red';
    ctx.lineWidth = 3;
    ctx.fillStyle = 'blue';
    ctx.moveTo(10, 200); // the starting point
    ctx.lineTo(10, 150); // I want this to have no stroke
    ctx.lineTo(110, 30); // stroked line
    ctx.lineTo(210, 50); // stroked line
    ctx.stroke(); // end our stroke here

    ctx.lineTo(210, 200); // line without a stroke
    ctx.fill();
}
draw();

提前感谢您的帮助

在beginPath()和fill()/stroke()之间只得到1个样式。

因此,要获得一个可选择笔画其分段的路径,您必须:

  • 单独绘制每个段,并选择是否应用描边

  • 重新绘制整个路径并填充

BTW,你应该开始所有的路径绘制命令context.beginPath()。如果没有,那么从最后一个beginPath开始的所有绘图也将在每次描边/填充期间重新绘制。

下面是示例代码:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var points=[];
    points.push({x:10,y:200,isStroked:false});
    points.push({x:10,y:150,isStroked:false});
    points.push({x:110,y:30,isStroked:true});
    points.push({x:210,y:50,isStroked:true});
    points.push({x:210,y:200,isStroked:false});
    points.push({x:10,y:200,isStroked:false});
    draw(points,"red","blue",3);
    function draw(points,stroke,fill,linewidth){
        ctx.strokeStyle=stroke;
        ctx.lineWidth=linewidth;
        ctx.fillStyle=fill;
        // draw strokes
        for(var i=1;i<points.length;i++){
            var p=points[i];
            if(p.isStroked){
                ctx.beginPath();
                ctx.moveTo(points[i-1].x,points[i-1].y);
                ctx.lineTo(points[i].x,points[i].y);
                ctx.stroke();            
            }
        }
        // draw fill
        ctx.beginPath();
        ctx.moveTo(points[0].x,points[0].y);
        for(var i=1;i<points.length;i++){
            ctx.lineTo(points[i].x,points[i].y);
        }
        ctx.fill();
    }
}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>