改变颜色

问题描述:

我试图改变线对动态画布绘制的颜色...改变颜色

ctx.moveTo(0, 0); 
ctx.lineTo(0, 200); 
ctx.strokeStyle = "Grey" 

这可能是鼠标悬停事件或按钮或鼠标点击事件,我想改变颜色线或使其大胆。是否可以通过添加事件来改变颜色,或者是否可以对特定元素上的事件给出样式?

我遇到了同样的问题,我用另一种颜色的不同的画布元素来移动另一条线,所以它给出了线的外观动态变化的颜色。

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

希望这能解决你的问题.... :)

非常接近。从某种意义上说,您无法真正“改变”画布上某个元素的颜色,因为it has no scene graph,或换句话说,它没有画布上绘制的内容的历史记录。要更改线条的颜色,您必须重绘线条。

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

如果画布上有更复杂的场景正在进行,则必须重绘整个场景。有许多Javascript库扩展了canvas标签的基本特征,并提供了其他绘图功能。你可能想看看Processing,它看起来相当令人印象深刻。

 
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)