Search code examples
html5-canvas

HTML5 canvas updating a color of an existing line - possible?


I am new to html5 and trying to get a handle on the fundamentals.

I'm wondering once I draw a line (say in black), is it possible for me to get a "pointer" to that line using the canvas's context and subsequently update the color of that line? Does that operation make sense in html5 land? Or do I have to redraw a new line on the exact same spot with the new color?

Thanks!


Solution

  • It's not possible to redraw your line because canvas/context does not "remember" where it drew your line.

    The common design pattern is to "remember" the line in a javascript object:

    var myLine={x0:10,y1:20,x1:100,y1:50};
    

    Then you can redraw the remembered line with a new color:

    context.strokeStyle=myNewColor;
    context.beginPath();
    context.moveTo(myLine.x0,myLine.y0);
    context.lineTo(myLine.x1,myLine.y1);
    context.stroke();
    

    Another possible glitch.

    Canvas will automatically anti-alias all of its path drawings. That means canvas may add anti-aliasing pixels to your first line which will remain even if you overwrite that first line.

    A common design pattern for canvas drawings is to "remember" all drawings and then completely erase & redraw all the remembered objects to the canvas.

    A useful new feature is being added to Html Canvas...

    In near future versions of canvas, there will be a Path Object built into the context that will "remember" path objects for you.