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?
window.addEventListener("load", function (event) {to the correct element and the correct event ->addEventListener("DOMContentLoaded", (event) => {see --> developer.mozilla.org/en-US/docs/Web/API/Document/…