0

I am trying to simply move the the cursor so that when it is between 200=x and 300=x the canvas background goes salmon and outside of that range it goes blue.

Here is my full attempt:

<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            margin: 10px;
            background: #ccc;
        }

        #my_canvas {
            background: #fff;
            border: #000 1px solid;
        }
    </style>
    <script>
        function initCanvas() {
            var ctx = document.getElementById("my_canvas").getContext("2d");
            ctx.canvas.addEventListener("mousemove", function (event) {
                var mouseX = event.clientX - ctx.canvas.offsetLeft;
                var mouseY = event.clientY - ctx.canvas.offsetTop;
                var status = document.getElementById("status");
                status.innerHTML = mouseX + " | " + mouseY;
            });
            ctx.canvas.addEventListener("click", function (event) {
                var mouseX = event.clientX - ctx.canvas.offsetLeft;
                var mouseY = event.clientY - ctx.canvas.offsetTop;
                // alert(mouseX+" | "+mouseY);
                ctx.fillStyle = "orange";
                ctx.fillRect(mouseX - 15, mouseY - 15, 30, 30);
            });
        }
        window.addEventListener("load", function (event) {
            initCanvas();
        });
    </script>
</head>

<body>
    <canvas id="my_canvas" width="500" height="300">
        <script>
            const ctx = my_canvas.getContext("2d");
            ctx.fillStyle = "salmon";
            // Create a Canvas:
            //const canvas = document.getElementById("myCanvas");
            // Define a new path
            ctx.beginPath();
            // Set a start-point
            ctx.moveTo(200, 150);
            // Set an end-point
            ctx.lineTo(200, 500);
            // The other vertical line
            ctx.moveTo(300, 150);
            ctx.lineTo(300, 500);
            ctx.stroke();
            if (mouseX > 200 && mouseX < 300) {
                ctx.fillStyle = "blue";
            }
            ctx.stroke();
        </script>
    </canvas>
    <h2 id="status">0 | 0</h2>
</body>

</html>

What can I try next?

1

4 Answers 4

2

You could add a check and set the color by condition.

function initCanvas() {
    const ctx = document.getElementById('my_canvas').getContext('2d');
    ctx.canvas.addEventListener('mousemove', function(event) {
        const
            mouseX = event.clientX - ctx.canvas.offsetLeft,
            mouseY = event.clientY - ctx.canvas.offsetTop,
            status = document.getElementById('status');

        status.innerHTML = mouseX + " | " + mouseY;
    });
    ctx.canvas.addEventListener('click', function(event) {
        const
            mouseX = event.clientX - ctx.canvas.offsetLeft,
            mouseY = event.clientY - ctx.canvas.offsetTop;
        
        ctx.fillStyle = mouseX >= 200 && mouseX <= 300
            ? 'orange'
            : 'blue';

        ctx.fillRect(mouseX - 15, mouseY - 15, 30, 30);
    });
}

const ctx = my_canvas.getContext("2d");
ctx.fillStyle = "salmon";
ctx.beginPath();
ctx.moveTo(200, 150);
ctx.lineTo(200, 500);
ctx.moveTo(300, 150);
ctx.lineTo(300, 500);
ctx.stroke();

window.addEventListener('load', initCanvas);
body { margin: 10px; background: #CCC; }
#my_canvas { background: #FFF; border: #000 1px solid; }
<canvas id="my_canvas" width="500" height="300">
</canvas>
<h2 id="status">0 | 0</h2>

Sign up to request clarification or add additional context in comments.

Comments

1

The big problem you're running into is that mouseX is not defined in your script tag. Generally speaking also, script tags should be nested within either head or body. I've updated your logic to fit all of your js within a script tag within the body:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Canvas Background Change</title>
        <style>
            body {
                margin: 10px;
                background: #CCC;
            }

            #my_canvas {
                display: block;
                margin: 0 auto;
                border: 1px solid #000;
            }
        </style>
    </head>

    <body id="my_body">
        <canvas id="my_canvas" width="500" height="300">
        </canvas>
        <script>
            function initCanvas() {
                const canvas = document.getElementById('my_canvas');
                const ctx = canvas.getContext('2d');

                // Initialize the canvas background to blue
                ctx.fillStyle = "blue";
                ctx.fillRect(0, 0, canvas.width, canvas.height);

                // Mouse move event listener
                canvas.addEventListener('mousemove', function (event) {
                    const mouseX = event.clientX - canvas.offsetLeft;

                    // Check if the mouse is within the specified range
                    if (mouseX >= 200 && mouseX <= 300) {
                        ctx.fillStyle = "salmon";
                    } else {
                        ctx.fillStyle = "blue";
                    }

                    // Redraw the entire canvas with the updated background color
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                });
            }

            window.addEventListener('load', initCanvas);
        </script>
    </body>

</html>

I wasn't quite sure what you meant with your condition with the colors: If you want the area that isn't your defined canvas to turn blue, you can style your body element to have the blue background

document.getElementById("my_body").style.backgroundColor = "blue"

If you only wanted the 200-300 range of your canvas to be salmon while the rest is blue, you could just draw a salmon colored rectangle over the blue canvas with this revised mousemove listener

const mouseX = event.clientX - canvas.offsetLeft;

// Clear the entire canvas before re-drawing (to remove the salmon color)
ctx.clearRect(0, 0, canvas.width, canvas.height);

// Draw the blue background
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Draw the salmon region when mouseX is within 200-300
if (mouseX >= 200 && mouseX <= 300) {
    ctx.fillStyle = "salmon";
    ctx.fillRect(200, 0, 100, canvas.height);
}

Comments

0

So, there's a couple of things to change:

  • If you want the rectangle to update every time the cursor moves, move the code drawing it to the mousemove event listener
  • Use the ctx.rect() function to draw rectangles
  • If you want to fill a rectangle use ctx.fill(), not ctx.stroke()
  • Define canvas to make changes to the DOM <canvas> element instead of accessing it with ctx.canvas for readability
  • Consider using const and let instead of var for better functionality
  • Consider not putting <script> tags inside of <canvas> tags

There's a functioning code snippet:

function initCanvas() {
    const canvas = document.getElementById("my_canvas");
    const ctx = canvas.getContext("2d");
    let mouseX = 0;
    let mouseY = 0;
    
    canvas.addEventListener("mousemove", function (event) {
        mouseX = event.clientX - canvas.offsetLeft;
        mouseY = event.clientY - canvas.offsetTop;
        
        const status = document.getElementById("status");
        status.innerHTML = mouseX + " | " + mouseY;
        
        ctx.fillStyle = "salmon";

        if (mouseX > 200 && mouseX < 300) {
            ctx.fillStyle = "blue";
        }

        // Create a Canvas:
        //const canvas = document.getElementById("myCanvas");

        // Define a new path
        ctx.beginPath();

        // Draw rect
        ctx.rect(200, 150, 100, 350);
        ctx.fill();
    });
    
    canvas.addEventListener("click", function (event) {
        mouseX = event.clientX - canvas.offsetLeft;
        mouseY = event.clientY - canvas.offsetTop;
        
        // alert(mouseX+" | "+mouseY);
        ctx.fillStyle = "orange";
        ctx.fillRect(mouseX - 15, mouseY - 15, 30, 30);
    });
}

window.addEventListener("load", function (event) {
    initCanvas();
});
body {
    margin: 10px;
    background: #ccc;
}

#my_canvas {
    background: #fff;
    border: #000 1px solid;
}
<canvas id="my_canvas" width="500" height="300"></canvas>
<h2 id="status">0 | 0</h2>

2 Comments

Seems I've dealt with all those suggestions. 1. I don't want to use rect because I'm changing the background not just putting a rectangle over it. That handles the first three bullet point. The fourth point, I'm not sure how to define <canvas>. I understand what you're saying that I shouldn't use var use let and const instead. I don't see the <script> tag inside the <canvas> but get how this would be a problem. Thanks
@ofey 1. what do you mean with background? what you were doing in the question was the same thing that rect() does, but more complicated. 2. i meant that you define and use a variable with the element instead of accessing it from the context: const canvas = document.getElementById("my_canvas"); const ctx = canvas.getContext("2d"); - so 2 separate variables. 3. what problem do you see with <script> outside of <canvas>?
0

function initCanvas(){
    var ctx = document.getElementById('my_canvas').getContext('2d');
    ctx.canvas.addEventListener('mousemove', function(event){
        var mouseX = event.clientX - ctx.canvas.offsetLeft;
        var mouseY = event.clientY - ctx.canvas.offsetTop;
        var status = document.getElementById('status');
        status.innerHTML = mouseX+" | "+mouseY;
    });
    ctx.canvas.addEventListener('mousemove', function(event){
        var mouseX = event.clientX - ctx.canvas.offsetLeft;
        var mouseY = event.clientY - ctx.canvas.offsetTop;
    var body = document.body;
    var select = document.getElementById( 'me' );
    body.style.background = "blue"
    if (mouseX > 200 && mouseX < 300){
        body.style.background = "salmon"
    } else{
        body.style.background = "blue"
    }
    });
}
window.addEventListener('load', function(event) {
    initCanvas();
});
const canvas = document.getElementById("my_canvas");
const ctx = canvas.getContext("2d");
  ctx.beginPath();
        ctx.moveTo(200,150);
        ctx.lineTo(200, 500);
        ctx.moveTo(300, 150);
        ctx.lineTo(300, 500);
        ctx.stroke();
body{ margin:10px; background:blue; }
#my_canvas{ background:#FFF; border:#000 1px solid; }
<!DOCTYPE html>
<html>
<head>
<style>
body{ margin:10px; background:blue; }
#my_canvas{ background:#FFF; border:#000 1px solid; }
</style>
<canvas id="my_canvas" width="500" height="300">
</canvas>
<script>
function initCanvas(){
    var ctx = document.getElementById('my_canvas').getContext('2d');
    ctx.canvas.addEventListener('mousemove', function(event){
        var mouseX = event.clientX - ctx.canvas.offsetLeft;
        var mouseY = event.clientY - ctx.canvas.offsetTop;
        var status = document.getElementById('status');
        status.innerHTML = mouseX+" | "+mouseY;
    });
    ctx.canvas.addEventListener('mousemove', function(event){
        var mouseX = event.clientX - ctx.canvas.offsetLeft;
        var mouseY = event.clientY - ctx.canvas.offsetTop;
    var body = document.body;
    var select = document.getElementById( 'me' );
    body.style.background = "blue"
    if (mouseX > 200 && mouseX < 300){
        body.style.background = "salmon"
    } else{
        body.style.background = "blue"
    }
    });
}
window.addEventListener('load', function(event) {
    initCanvas();
});
const canvas = document.getElementById("my_canvas");
const ctx = canvas.getContext("2d");
  ctx.beginPath();
        ctx.moveTo(200,150);
        ctx.lineTo(200, 500);
        ctx.moveTo(300, 150);
        ctx.lineTo(300, 500);
        ctx.stroke();
</script>
</head>
<body id="me">
<h2 id="status">0 | 0</h2>
</body>  
</html

I'll give the full text here of what I did and how I got it to work.

I didn't explain myself well or clearly; what I wanted was it to have the background blue when the cursor is to left and right of the vertical lines and to go salmon when it is in between. I have it working exactly as I want it now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.