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
Any help would be greatly appreciated.
Thanks,
Shane
2
Answers
You could add a check and set the color by condition.
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 eitherhead
orbody
. I’ve updated your logic to fit all of your js within a script tag within thebody
: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
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