Javascript 如何使线变成红色和蓝色?

Javascript 如何使线变成红色和蓝色?,javascript,jquery,html,html5-canvas,Javascript,Jquery,Html,Html5 Canvas,我有,这对路径很有效: 但是我需要红色开始,蓝色结束,我试着把context.strokeStyle='BLUE';但它失败了 你知道怎么做吗 canvas.width = canvas.height = 500; var context = canvas.getContext('2d'); var shape = new Path2D(); function init(){ context.lineWidth = 1; context.strokeStyle = 'red'; // R

我有,这对路径很有效:

但是我需要红色开始,蓝色结束,我试着把context.strokeStyle='BLUE';但它失败了

你知道怎么做吗

canvas.width = canvas.height = 500;
var context = canvas.getContext('2d');
var shape = new Path2D();

function init(){
context.lineWidth = 1;
context.strokeStyle = 'red';


// RED RED RED
shape.moveTo(100,20);
shape.lineTo(200, 160);
shape.quadraticCurveTo(0, 200, 250, 120);
shape.bezierCurveTo(290, -40, 300, 200, 400, 150);


// BLUE BLUE
//---- make this BLUE BLUE BLUE BLUE not RED RED RED
//---- make this BLUE BLUE BLUE BLUE not RED RED RED
// line 2 
//---- make this BLUE BLUE BLUE BLUE not RED RED RED
//---- make this BLUE BLUE BLUE BLUE not RED RED RED
shape.lineTo(500, 90);

draw();
}    

var pos = 0;
var l = 760;
function draw() {
    context.clearRect(0,0,canvas.width, canvas.height);
    context.setLineDash([pos, l-pos]);
    context.stroke(shape);
    pos = pos+3;
    if(pos >= l){
        blink();
        return;
        }
    requestAnimationFrame(draw);
};
var i = 0;
function blink(){
    context.clearRect(0,0,canvas.width, canvas.height);
    if((++i % 30) > 15){
        context.stroke(shape);
        }

    requestAnimationFrame(blink);
    };
init();

使用渐变样式笔划

var gradient=context.createLinearGradient(0,0,170,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");

// Fill with gradient
context.strokeStyle=gradient;
context.lineWidth=5;

使用
canvas
API的
strokeStyle
属性来获得所需的颜色。下面是一个例子:

var ctx=c.getContext("2d");
ctx.strokeStyle="#0000FF"; //  Change color to blue
ctx.strokeRect(20,20,150,100); 
绘制一个蓝色矩形

由于您使用的是
Path2D
,因此必须使用不同的
path
来绘制不同的
颜色

下面是一个通过动画实现的示例。

<canvas id="canvas" style="border:1px solid;">
</canvas>

<script>
var canvas=document.getElementById("canvas");
canvas.width = canvas.height = 600;
var context = canvas.getContext('2d');

// Array of shapes which has different colors
var shapes = [ new Path2D(),   // RED shape
               new Path2D()    // BLUE shape
];

// Parallel Array to store color for each shape
var colors = [
                "#ff0000", // RED
                "#0000ff"  // BLUE
];

// Parallel Array to store length of each shape
var length_of_shapes =[
    644,        // Approx Length of RED shape
    116         // Length of Blue shape
];

var pos=0;      // Position 

var l=0;        // Total length

function init(){
    context.lineWidth = 1;

    // RED Shape
    shapes[0].moveTo(100,20);
    shapes[0].lineTo(200, 160);
    shapes[0].quadraticCurveTo(0, 200, 250, 120);
    shapes[0].bezierCurveTo(290, -40, 300, 200, 400, 150);

    // BLUE Shape
    shapes[1].moveTo(400, 150);
    shapes[1].lineTo(500, 90);

    calcTotalLength();
    draw();
}    


// Function to calculate total length
function calcTotalLength(){
    for (var i = 0; i < length_of_shapes.length; i++) {
        l+=length_of_shapes[i];
    };
}


// Function to draw a shape at index i
function drawShape(i){
    context.strokeStyle = colors[i];
    context.stroke(shapes[i]);
}


function draw() {
    var length_of_prev_shapes=0;

    context.clearRect(0,0,canvas.width, canvas.height);     // Clear the canavas

    for (var i = 0; i < shapes.length; i++) {
        if(pos < (length_of_prev_shapes + length_of_shapes[i])){        // If the current shape is still drawing

            // Is this the first shape then position is pos else it is the remainder of pos divided by length_of_prev_shapes
            var tmpPos=(length_of_prev_shapes !== 0) ? (pos % length_of_prev_shapes) : pos; 

            context.setLineDash([ tmpPos, (length_of_shapes[i] - tmpPos) ]);        // Add drawing effect

            drawShape(i);       // Draw Shape at i

            // If the current shape is still drawing no point in looping through all other shapes so break
            break;      
        }else{                          
            context.setLineDash([0]);   // Remove the drawing effect

            // Add the length of the current shape to the length of all other drawn shapes
            length_of_prev_shapes += length_of_shapes[i];   

            drawShape(i);       // Draw Shape at i
        }
    };

    pos+=3;     // Increase position by 3

    // If all the points are drawn i.e the position is greater than length
    if(pos >= l){   
        blink();    // Blink
        return;
    }

    requestAnimationFrame(draw);
}

var i = 0;
function blink(){
    context.clearRect(0,0,canvas.width, canvas.height);
    if((++i % 30) > 15){
        for(var j=0;j < shapes.length;j++){
            drawShape(j);
        }
    }
    requestAnimationFrame(blink);
}
init();
</script>

var canvas=document.getElementById(“canvas”);
canvas.width=canvas.height=600;
var context=canvas.getContext('2d');
//具有不同颜色的形状数组
var shapes=[new Path2D(),//红色形状
新建Path2D()//蓝色形状
];
//并行数组,用于存储每个形状的颜色
变量颜色=[
“#ff0000”//红色
“#0000ff”//蓝色
];
//并行数组以存储每个形状的长度
形状的变量长度=[
644,//红色形状的大致长度
116//蓝色形状的长度
];
var pos=0;//位置
变量l=0;//全长
函数init(){
context.lineWidth=1;
//红色形状
形状[0]。移动到(100,20);
形状[0].lineTo(200160);
形状[0]。方形曲线(0,200,250,120);
形状[0]。贝塞尔曲线图(290,-40300200400150);
//蓝色形状
形状[1]。移动到(400150);
形状[1].lineTo(500,90);
calcTotalLength();
draw();
}    
//用于计算总长度的函数
函数calcTotalLength(){
对于(var i=0;i=l){
闪烁();//闪烁
返回;
}
请求动画帧(绘制);
}
var i=0;
函数blink(){
clearRect(0,0,canvas.width,canvas.height);
如果(++i%30)>15){
对于(var j=0;j
使用此方法的优点

  • 它很容易使用
  • 它很容易理解,因为它有很好的文档记录
  • 这将产生问题所要求的确切效果
  • 此方法的缺点

  • 首先,您必须找到所有
    形状
    长度
    ,此处未介绍
  • 找到曲线的长度可能有点吓人
  • 动画的
    速度
    取决于
    曲线的
    长度
    精度
    ,这将减少调用
    绘制
    函数的频率
  • 要更改
    形状部分的
    颜色
    ,必须定义不同的
    形状

  • 要使用
    Path2D

    绘制,请检查我的答案。看看我的答案,它会给你想要的确切效果…兄弟,我认为这不是推荐的过程!如果我错了,请纠正我。@问,你错了。不推荐的做法是在动画循环中创建太多不同的渐变,但在这里,您只能在初始阶段创建一次,使用它也很好。此技巧的主要问题是线性渐变就像覆盖上下文的完整矩形区域。这意味着它实际上并没有沿着路径走:为了避免这种情况,你必须独立地画出路径上的每一点:是的,正是。。。。但是OP并没有要求他要它跟随他的路线根据这个问题…你要如何将它与setLineDash混合?谢谢,希望我能回答这两个问题。嗯,它还是有点固定,不是吗?只是快速看了一下,但是如果你想改变颜色阈值的位置,你还必须重写整个路径声明,不是吗@是的。。但从好的方面看,你会确切地知道你的形状是什么颜色,但如果你使用渐变,这是不可能做到的。。。