【问题标题】:Canvas single line with stroke in shape画布单线,形状为笔划
【发布时间】:2012-10-16 18:49:21
【问题描述】:

我正在使用 HTML5 Canvas 开发一个显示形状集合的应用程序。在每个形状上,我希望其中一个形状边有一个笔触,但如果不给所有边一个笔触或使用单独的线条并打破形状,阻止它进行填充,就无法做到这一点。

我如何绘制一个在一侧有笔触和填充的形状?

提前致谢。

【问题讨论】:

    标签: html canvas


    【解决方案1】:

    一种方法是在您没有完全完成路径时调用 stroke ,从而只抚摸您已经绘制的内容。显然,如果你不先画出你想要抚摸的边,这是行不通的,所以下面还有另一个选项。

    ​var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d");
    
    canvas.width = canvas.height = 256;
    
    ​ctx.fillStyle = "red";
    ctx.strokeStyle = "black";
    ctx.lineWidth = 2;
    
    ctx.beginPath();
    ctx.moveTo(50,50);
    ctx.lineTo(100,100);
    ctx.stroke();
    ctx.lineTo(100,200);
    ctx.lineTo(50,100);
    ctx.lineTo(50,50);
    ctx.fill();
    

    Live Demo

    这只是一个快速的概念验证功能,作为实现您正在寻找的另一种方式。

    Live Demo 2

    var shape = [{x:50,y:50}, {x:100, y:100}, {x:100, y:200}, {x:50,y:100}, {x:50, y:50}];
    
    function drawShape(shape, strokeIndex){
        ctx.beginPath();
        ctx.moveTo(shape[0].x, shape[0].y);
    
        for(var i = 1; i < shape.length; i++){
            ctx.lineTo(shape[i].x, shape[i].y);   
        }
        ctx.closePath();
        ctx.fill();
    
        // stroke
        ctx.beginPath();
        ctx.moveTo(shape[strokeIndex-1].x, shape[strokeIndex-1].y);
        ctx.lineTo(shape[strokeIndex].x, shape[strokeIndex].y);
        ctx.stroke();
    }
    
    drawShape(shape, 3);
    

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2019-03-03
      相关资源
      最近更新 更多