Why is Javascript automatically blending my colors?

后端 未结 2 550
盖世英雄少女心
盖世英雄少女心 2021-01-13 20:33

I\'m just starting out with Javascript and HTML5 so it\'s entirely likely that I\'m making some really dumb mistake. In fact I hope that\'s all it is and that this is an ea

相关标签:
2条回答
  • 2021-01-13 21:15

    This is not blending, it's just that the stroke is 1 pixel wide, and the coordinates in canvas are those of squares, while lines go between squares. Your lines go between pixels and are anti-aliased. If you want your strokes to align with pixels, you need to use coordinates like (99.5,99.5), not (100,100). Hard to describe, but there is plenty of documentation available.

    To make long story short, you have to translate the whole drawing code by 0.5,0.5. Try something like:

    ctx.save();
    ctx.translate(0.5,0.5);
    
    ctx.clearRect(50, 50, 100, 100);
    
    ctx.fillStyle = "rgb(240, 240, 240)";
    ctx.fillRect(0, 0, 100, 100);
    
    ctx.strokeStyle="rgb(0, 0, 255)";
    ctx.strokeRect(20,20,150,100);
    ctx.restore(); 
    
    0 讨论(0)
  • 2021-01-13 21:26

    Check out the globalCompositeOperation option. Seems like you had set it to "lighter", while you want the default "source-over".

    0 讨论(0)
提交回复
热议问题