Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multicolors in canvas LineTo

Tags:

html

canvas

function TrackGraphic(model, canvas) {
    //TrackModel
    this._model = model;
    this.draw = function(context) {
        var dx = Math.cos(this._model.startAngle + Math.PI / 2);
        var dy = Math.sin(this._model.startAngle + Math.PI / 2);

        context.beginPath();
        context.lineWidth = 10;
        context.moveTo(this._model.offsetX, this._model.offsetY);
        //CurvePoint
        var p;
        for (var d = 0; d < this._model.length; d += 1) {
            if (d > 1000) {

                console.log('2F2F2F');
                context.strokeStyle = "#2F2F2F" //"rgb(255,165,0)"; //0x2F2F2F

            } else {
                context.strokeStyle = "#FFF" //"rgb(255,165,0)"; //0x2F2F2F;
                console.log('FFFFFF');


            }
            p = this._model.getTrackPoint(d);
            context.lineTo(this._model.offsetX + p.x, this._model.offsetY + p.y)
        }
        context.stroke();
    }
}​

The above code produces the lines in the canvas. The line is one color, I want to at the beginning or in any municipal color was different. My code does not work: (why?. How to fix it?

like image 646
Piotr Stanek Avatar asked May 13 '12 13:05

Piotr Stanek


1 Answers

Changing the color while you are constructing the path doesn't do anything. The color is applied only once, when stroke() is called, so the last strokeStyle you set will be the color of the entire line.

beginPath(), moveTo(), lineTo(), etc only create a path and that path itself has no color. Stroking or filling that path only ever apply a single color.

If you want a path that is multiple colors you will have to do one of two things:

Begin a path, do some number of lines, stroke it one color, and then begin another path that will be stroked with a different color. In other words:

// make a red line segment
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x, y);
ctx.strokeStyle = 'red';
ctx.stroke();
// Begin a new path and make this line segment green
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x, y);
ctx.strokeStyle = 'green';
ctx.stroke();
//etc

Or, depending on what you're doing you could also use a linearGradient

like image 125
Simon Sarris Avatar answered Sep 30 '22 16:09

Simon Sarris