Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

meu preventDefault() não funciona

Ao tentar alternativas para pintar bolas de cores diferentes acabei conseguindo criar quatro opções de cores diferentes (vide código). Ficou legal, porém ao clicar com o botão esquerdo ele pinta a bola e abre o menu de opções, mesmo colocando o preventDefault. Alguém teria alguma sugestão?

<meta charset = "UTF-8">
<canvas id="canvas1" width="600" height="400" />



<script>

var mainFrame = document.getElementById("canvas1");

var mainBrush = mainFrame.getContext("2d");

mainBrush.fillStyle = "gray";
mainBrush.fillRect(0,0,600,400);

var drawBlueBall = function(x,y) {

    mainBrush.fillStyle = "blue"
    mainBrush.beginPath();
    mainBrush.arc(x, y, 10, 0, 2 * Math.PI);
    mainBrush.fill();
    console.log("drawBlueBall");

}

var drawRedBall = function(x,y) {
    mainBrush.fillStyle = "red"
    mainBrush.beginPath();
    mainBrush.arc(x, y, 10, 0, 2 * Math.PI);
    mainBrush.fill();
    console.log("drawRedBall");
}

var drawGreenBall = function(x,y) {
    mainBrush.fillStyle = "green"
    mainBrush.beginPath();
    mainBrush.arc(x, y, 10, 0, 2 * Math.PI);
    mainBrush.fill();
    console.log("drawGreenBall");
}

var drawWhiteBall = function(x,y) {
    mainBrush.fillStyle = "White"
    mainBrush.beginPath();
    mainBrush.arc(x, y, 10, 0, 2 * Math.PI);
    mainBrush.fill();
    console.log("drawWhiteBall");
}

var leftClick = function (mouseEvent) {
    mouseEvent.preventDefault();
    var x = mouseEvent.pageX - mainFrame.offsetLeft;
    var y = mouseEvent.pageY - mainFrame.offsetTop;
    var altKey = mouseEvent.altKey;
    console.log("Alguém clicou no canvas na posição " + x + ", " + y);
    console.log(altKey);

    if (altKey == true) {
        drawWhiteBall(x,y);
    } else {
        drawGreenBall(x,y);
    }


}

var rightClick = function (mouseEvent) {
    var x = mouseEvent.pageX - mainFrame.offsetLeft;
    var y = mouseEvent.pageY - mainFrame.offsetTop;
    var altKey = mouseEvent.altKey;
    console.log("Alguém clicou no canvas na posição " + x + ", " + y);
    console.log(altKey);

    if (altKey == true) {
        drawRedBall(x,y);
    } else {
        drawBlueBall(x,y);
    }



}

mainFrame.onclick = leftClick;
mainFrame.oncontextmenu = rightClick;

</script>
2 respostas
solução!

Lucas você ta se confundindo, o botão direito é que abre o menu e não o esquerdo, você tem que usar o preventDefault() na função rightClick

Opa, foi isso mesmo. Obrigado por ler o meu código.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software