I have a responsive canvas with and it draw a square on mousemove, however I cannot target the mouse position of the canvas, however it works if the canvas is not responsive. how can I target the position of the mouse? Thank you in advance.
https://jsfiddle.net/Paul017/yz028mwe/3/
This is the code.
HTML:
<h4>Drag the mouse to create a rectangle</h4>
<canvas id="canvas" width=300 height=300></canvas>
CSS:
body{ background-color: ivory; }
#canvas{border:1px solid red; width:100%}
JS: var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d");
ctx.strokeStyle = "rgba(255, 235, 59, 0.5)";
ctx.fillStyle = "red";
ctx.fill();
ctx.lineWidth = 1;
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var isDown = false;
var startX;
var startY;
function handleMouseDown(e) {
e.preventDefault();
e.stopPropagation();
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
// set a flag indicating the drag has begun
isDown = true;
}
function handleMouseUp(e) {
e.preventDefault();
e.stopPropagation();
isDown = false;
}
function handleMouseOut(e) {
e.preventDefault();
e.stopPropagation();
isDown = false;
}
function handleMouseMove(e) {
e.preventDefault();
e.stopPropagation();
// if we're not dragging, just return
if (!isDown) {
return;
}
// get the current mouse position
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
ctx.clearRect(0, 0, canvas.width, canvas.height);
var width = mouseX - startX;
var height = mouseY - startY;
ctx.strokeRect(startX, startY, width, height);
}