I am trying to change the color of line drawn on canvas dynamically...
ctx.moveTo(0, 0);
ctx.lineTo(0, 200);
ctx.strokeStyle = "Grey"
开发者_JS百科
It could be mouseover event or press botton or mouse click event, I want to change the color of line or make it bold. Is it possible to change the color by adding event or is it possible to give style on an event on particular element?
Very close. In a sense, you can't really "change" the color of an element on the canvas because it has no scene graph, or, in other words, it has no history of what has been drawn on the canvas. To change the color of a line, you would have to redraw the line.
ctx.moveTo(0, 0);
ctx.lineTo(0, 200);
ctx.strokeStyle = "Grey";
ctx.stroke();
// To make the line bold and red
ctx.moveTo(0, 0);
ctx.lineTo(0, 200);
ctx.strokeStyle = "Red";
ctx.lineWidth = 5;
ctx.stroke();
If the canvas had a more complex scene going on, you would have to redraw the entire scene. There are numerous Javascript libraries that extend the base features of the canvas tag, and provide other drawing capabilities. You may want to take a look at Processing, it looks quite impressive.
I was having the same problem, I did it by moving another line with another color of different canvas element, so it gives appearance of line changing its color dynamically.
function drawGreyLine() {
ctx1.clearRect(0, 0, WIDTH, HEIGHT);
ctx1.strokeStyle = "Grey"; // line color
ctx1.moveTo(0, 0);
ctx1.moveTo(0, 200);
ctx1.lineTo(200, 200);
}
function drawColorLine() {
x += dx;
if (x <= 200) {
ctx2.beginPath();
ctx2.lineWidth = 5;
ctx2.lineCap = "round";
ctx2.strokeStyle = "sienna"; // line color
ctx2.moveTo(0, 200);
ctx2.lineTo(x, 200);
ctx2.moveTo(200, 200);
ctx2.stroke();
}
}
Hope this solves your problem.... :)
var canvas = document.getElementById('canvas'); var ctx=canvas.getContext('2d'); var line1={x:10,y:10, l:40, h:1} var down=false; var mouse={x:0,y:0} canvas.onmousemove=function(e){ mouse={x:e.pageX-this.offsetLeft,y:e.pageY-this.offsetTop}; this.onmousedown=function(){down=true}; this.onmouseup=function(){down=false} ; } setInterval(function(){ ctx.clearRect(0,0,canvas.width,canvas.height) ctx.beginPath() ctx.moveTo(line1.x,line1.y) ctx.lineTo(line1.x +line1.l,line1.y) ctx.lineTo(line1.x +line1.l,line1.y+line1.h) ctx.lineTo(line1.x,line1.y+line1.h) ctx.isPointInPath(mouse.x,mouse.y)? (ctx.fillStyle ="red",line1.x=down?mouse.x:line1.x,line1.y=down?mouse.y:line1.y):(ctx.fillStyle ="blue") ctx.fill() },100)
精彩评论