javascript - 是否可以在 Canvas 的同一路径上使用两种不同的笔触样式?

标签 javascript html canvas

是否可以在 Canvas 中创建一个路径,其中线条的描边方式不同?例如,你可以画一个盒子,里面是绿色的,有 4 个不同颜色的边。我包含了一些代码,但这不起作用,因为它绘制了两次路径(第一次是未完成的路径,第二次是整个路径)。

JavaScript

window.onload = function()
{
    canvas = document.getElementById("canvas1");
    if (canvas.getContext)
    {
        ctx = canvas.getContext("2d");
        ctx.beginPath();                
        ctx.save();                
        ctx.moveTo(0, 0);
        ctx.strokeStyle = "rgb(255, 0, 0)";            
        ctx.lineTo(100, 100);
        ctx.stroke();
        ctx.strokeStyle = "rgb(0, 0, 255)";
        ctx.lineTo(200, 100);
        ctx.stroke();                
        ctx.restore();
    }                
}

HTML

<canvas id = "canvas1" width = "400" height = "400">
    Your browser does not support the HTML5 canvas tag.
</canvas>

最佳答案

我认为您必须使用两条路径。

    ctx = canvas.getContext("2d");
    ctx.beginPath();                              
    ctx.moveTo(0, 0);          
    ctx.lineTo(100, 100);
    ctx.strokeStyle = "rgb(255, 0, 0)";
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(100, 100);
    ctx.lineTo(200, 100);
    ctx.strokeStyle = "rgb(0, 0, 255)";
    ctx.stroke();

关于javascript - 是否可以在 Canvas 的同一路径上使用两种不同的笔触样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15296974/

相关文章:

javascript - Angular 选择 ng-selected 不起作用(使用 <option ng-repeat>)

javascript - 窗口关闭();不能在 Firefox 中工作

android - 使用 AspectRatio android Canvas 缩小大图像

javascript - 使用参数计算 JavaScript 函数内的平均值

javascript - 使用 $scope.apply() 后点击展开不工作

c# - 当逻辑需要 C# 和 Javascript 实现时如何保持 DRY?

javascript - 从浏览器将图像保存到手机图库

python - 在 Django 提交表单中输入错误格式(日期时间格式)时如何打印错误?

javascript - 镜像网络摄像头图像的右半部分

javascript - 使用 SetInterval 添加缓动和增量值