0

I'm trying to clear one line by drawing another one on top of it on HTML canvas. But the second line becomes semi transparent for some unknown to me reason.

index.html

<!DOCTYPE html>
<head>
    <script src="scripts.js" type="text/javascript"></script>
</head>
<html>

    <body onload = "onload()">
        <canvas id = "canvas" style="border: solid 1px; width: 200px; height: 200px;"></canvas>
    </body>
</html>

scripts.js

var canvas,ctx;
const onload = () =>{
    canvas = document.querySelector("#canvas")
    ctx = canvas.getContext('2d')
    drawLine("#ff0000")
    drawLine("#ffffff")
}

const drawLine = (color) =>{
    ctx.beginPath()
    ctx.strokeStyle = color
    ctx.moveTo(0,0)
    ctx.lineTo(200,200)
    ctx.stroke()
    ctx.closePath()
}

var canvas,ctx;
const onload = () =>{
    canvas = document.querySelector("#canvas")
    ctx = canvas.getContext('2d')
    drawLine("#ff0000")
    drawLine("#ffffff")
}

const drawLine = (color) =>{
    ctx.beginPath()
    ctx.strokeStyle = color
    ctx.moveTo(0,0)
    ctx.lineTo(200,200)
    ctx.stroke()
    ctx.closePath()
}
<!DOCTYPE html>
<head>
    <script src="scripts.js" type="text/javascript"></script>
</head>
<html>

    <body onload = "onload()">
        <canvas id = "canvas" style="border: solid 1px; width: 200px; height: 200px;"></canvas>
    </body>
</html>
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
rspx
  • 1
  • 1
  • First of all, `width` and `height` of a `` should be set as attributes, not as CSS properties. See [Canvas is stretched when using CSS but normal with "width" / "height" properties](/q/2588181/4642212). Please see [How to create Stack Snippets](//meta.stackoverflow.com/q/358992/4642212). I don’t see a second line. Also, the `ctx.closePath()` at the end does nothing. Remove it. – Sebastian Simon Dec 12 '21 at 14:49
  • Converted your code into a snippet. I do not see a problem with it. Maybe something inside your project is problematic that you did not share here. – Lajos Arpad Dec 12 '21 at 15:12
  • 1
    If you set `ctx.lineWidth = 10` you will see that the problem is not the opacity of the new line but the old line leaking from the edges. – aerial Dec 12 '21 at 15:18
  • 1
    This question might be of interest: https://stackoverflow.com/questions/195262/can-i-turn-off-antialiasing-on-an-html-canvas-element – Rikku Dec 12 '21 at 16:02

0 Answers0