Soldat2283
@Soldat2283

Не правильное расположение линии относительно курсора canvas?

По уроку сделал банальную рисовалку на js и решил добавить сверху кнопки добавил и теперь когда я рисую то что я рисую рисуется ниже курсора на сантиметра 2
А если без кнопок и тд тоесть чисто canvas то всё норм
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Canvas</title>
</head>
<body style="overflow: hidden">
    <div class="buttons">
        <button class="but">Очистить</button>
        <button class="but">Сохранить</button>
        <button class="but">Возпроизвести</button>
        <button class="but">Ластик</button>
    <input type="color" class="color">
    </div>
    <canvas id="canvas">Update browser!</canvas>
    <script src="script.js"></script>
</body>
</html>


let 
    filter = document.querySelector(".filter")
    canv = document.getElementById("canvas")
    ctx  = canv.getContext("2d")
    isMouseDown = false
    coords = []

canvas.width = 2000;
canvas.height = 2000;

//Code

canv.addEventListener("mousedown",function(){
    isMouseDown = true
})

canv.addEventListener("mouseup",function(){
    isMouseDown = false
    ctx.beginPath()
    coords.push("mouseup")
})

ctx.lineWidth = 10 * 2
canv.addEventListener("mousemove", function(e) {

        if( isMouseDown )
        {
            
            coords.push([e.clientX, e.clientY])
            
            ctx.strokeStyle = "orange"
            ctx.lineTo(e.clientX, e.clientY);
            ctx.stroke()
        
            ctx.fillStyle = "orange"
            ctx.beginPath()
            ctx.arc(e.clientX, e.clientY, 10, 0, Math.PI * 2);
            ctx.fill()
        
            ctx.beginPath()
            ctx.moveTo(e.clientX, e.clientY)
        }
})

function save(){
    localStorage.setItem("coords",JSON.stringify(coords))
}

function clear(){
    ctx.fillStyle = "white"
    ctx.fillRect(0, 0, canv.width, canv.height)
    ctx.beginPath()
    ctx.fillStyle = "orange"
}

function replay(){
    let timer = setInterval(function(){
        if (!coords.length){
            clearInterval(timer)
            ctx.beginPath(timer)
            return
        }

        let 
            crd = coords.shift()
            e = {
                clientX: crd["0"],
                clientY: crd["1"]
            }

        ctx.lineTo(e.clientX, e.clientY);
        ctx.stroke()
        
        ctx.beginPath()
        ctx.arc(e.clientX, e.clientY, 10, 0, Math.PI * 2);
        ctx.fill()
        
        ctx.beginPath()
        ctx.moveTo(e.clientX, e.clientY)
    },50)
}

document.addEventListener("keydown",function(e){
    if (e.keyCode === 83){
        //save

        save()
        console.log("Saved")
    }

    if (e.keyCode === 82){
        //replay

        console.log("Replaying...")
        coords = JSON.parse(localStorage.getItem("coords"))
        clear()
        replay()
    }

    if (e.keyCode === 67){
        //clear

        clear()
        coords = []
        console.log("Cleared")
    }
})


button.but {
    color: white;
    font-weight: 700;
    user-select: none;
    padding: .5em 2em;
    outline: none;
    border: 0px solid;
    border-radius: 1px;
    transition: 0.2s;
    height: 50px;
    width: auto;
    color: black;
} 

button.but:hover { 
    background: rgba(212, 208, 208, 0.2); 
}

button.but:active { 
    background: white; 
}

input.color {
    background-color: transparent;
    padding: 0px;
    margin: 0px;
    outline: none;
    border: 2px solid;
    border-radius: 1px;
    transition: 0.2s;
    height: 50px;
    width: 100px;
    border: none;
    display: inline-block;
} 

input.color:hover { 
    background-color: transparent; 
}

input.color:active { 
    background-color: transparent;
    border: none; 
}


.buttons{
    text-align: center;
    margin-bottom: 0px;
    padding: 15px;
    background-color: rgb(78, 76, 76);
}

#canvas{
    border: 2px solid orange;
}


5f5a7bb3c4a74675857749.png
  • Вопрос задан
  • 92 просмотра
Решения вопроса 1
@dennis_d
One Love, One Front-End
попробуй position: absolute для контейнера с кнопками
.buttons{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    text-align: center;
    margin-bottom: 0px;
    padding: 15px;
    background-color: rgb(78, 76, 76);
}

Проверил, работает
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы