Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
HTML5 Canvas drawing cursor is out of his actual position

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

})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!