Reputation: 2881
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!
Upvotes: 1
Views: 1032
Reputation: 11
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
function myColor(){
ctx.beginPath()
ctx.strokeStyle = document.getElementById("colorChange").value;
ctx.moveTo(50,50);
ctx.lineTo(100,100);
ctx.stroke()
}
window.onload = myColor()
<canvas id = "myCanvas" width = "400" height = "400"></canvas>
<input type = "color" id = "colorChange" oninput = myColor() value = "#ff0000">
Upvotes: 0
Reputation: 105015
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.
Upvotes: 1