Change color of canvas element

后端 未结 3 728
遥遥无期
遥遥无期 2021-01-29 04:26

I am trying to change the color of line drawn on canvas dynamically...

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

It coul

相关标签:
3条回答
  • 2021-01-29 05:04

    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.

    0 讨论(0)
  • 2021-01-29 05:07

    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.... :)

    0 讨论(0)
  • 2021-01-29 05:28
    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)
    
    0 讨论(0)
提交回复
热议问题