Home > database >  HTML5 Canvas drawing cursor is out of his actual position
HTML5 Canvas drawing cursor is out of his actual position

Time:07-10

I am trying to create HTML canvas drawing, but the drawing cursor is out of his actual position.

Here is the entire JavaScript/CSS/HTML code: HTML5 Canvas drawing

I think, the problem is in the JavaScript code, but I can't fix it.

Here is the JavaScript code:

let canvas = document.getElementById("canvas")
canvas.height = window.innerHeight
canvas.width = window.innerWidth
let ctx = canvas.getContext("2d")
ctx.lineWidth = 5

let prevX = null
let prevY = null

let draw = false

let clrs = document.querySelectorAll(".clr")
clrs = Array.from(clrs)
clrs.forEach(clr => {
    clr.addEventListener("click", () => {
        ctx.strokeStyle = clr.dataset.clr
    })
})

let clearBtn = document.querySelector(".clear")
clearBtn.addEventListener("click", () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
})


window.addEventListener("mousedown", (e) => draw = true)
window.addEventListener("mouseup", (e) => draw = false)

window.addEventListener("mousemove", function(e){
    if(prevX == null || prevY == null || !draw){
        prevX = e.clientX
        prevY = e.clientY
        return
    }

    let mouseX = e.clientX
    let mouseY = e.clientY
    ctx.beginPath()
    ctx.moveTo(prevX, prevY)
    ctx.lineTo(mouseX, mouseY)
    ctx.stroke()
    prevX = e.clientX
    prevY = e.clientY

})

CodePudding user response:

Set the height and width on your canvas in the html rather than CSS.

You have set your canvas size to be 100x100: <canvas id="canvas" width="100" height="100"></canvas>. So when you set the size in CSS, it effectively "stretches" the canvas to that size.

Changing it to <canvas id="canvas" width="1600" height="700"></canvas> and removing the height and width in your CSS will do the trick.

  • Related