如何使线条红色和蓝色?

时间:2016-12-13 07:59:17

标签: javascript jquery html5 html5-canvas

我有this code,它适用于路径:

enter image description here

但我需要开始RED和结束行BLUE,我尝试将context.strokeStyle =' blue&#39 ;;但它失败了。

你知道怎么做吗?

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();

2 个答案:

答案 0 :(得分:4)

使用渐变样式笔触

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;

http://www.w3schools.com/tags/canvas_strokestyle.asp

答案 1 :(得分:2)

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

var ctx=c.getContext("2d");
ctx.strokeStyle="#0000FF"; //  Change color to blue
ctx.strokeRect(20,20,150,100); 

绘制一个蓝色矩形。

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

以下是使用动画实现它的示例。

<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>

使用此方法的优点

  1. 它易于使用。
  2. 它很容易理解,因为它记录得很好。
  3. 它会给出问题所要求的确切效果。
  4. 此方法的缺点

    1. 您首先必须找到此处未涵盖的所有length的{​​{1}}。
    2. 找到曲线的长度可能有点令人生畏。
    3. shape的{​​{1}}取决于speed animation accuracylength将允许调用curves函数不太常见。
    4. 要更改draw部分的color,您必须定义不同的shape
    5. More details here!

      An Example使用shape

      进行绘制