I been searching around to find how to get the mouse position relative to canvas but without a JS library...can't see to find any examples except for jquery!
I use this to start my function:
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown", mousePos, false);
But e.pageX and e.pageY is affected by the position of the canvas. I need to remove that issue so the maths is correct so its only based on the canvas.
Can this be done without a JS library? As I have only ever seen it done with jquery which i'm trying to avoid as much as possible.
var findPos = function(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return { x : curleft, y : curtop };
};
Get the position of the canvas element and subtract the x and y from it.
I'm using :
var x;
var y;
if (e.pageX || e.pageY)
{
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;
First you need to get the offset of the canvas element, or how far right + down it is from the top-left corner.
When the mouse moves, factor in the offset variables to the mouse's position.
This code should do the trick:
var canvas = document.getElementById("canvas");
var xOff=0, yOff=0;
for(var obj = canvas; obj != null; obj = obj.offsetParent) {
xOff += obj.scrollLeft - obj.offsetLeft;
yOff += obj.scrollTop - obj.offsetTop;
}
canvas.addEventListener("mousemove", function(e) {
var x = e.x + xOff;
var y = e.y + yOff;
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, 100, 100);
ctx.fillText(x + " - " + y, 40, 40);
}, true);
Related
I want to add 4 text boxes which will give me the coordinates of a rectangle and if I manually edit the coordinates it should change /alter the rectangle as well.
Please tell me how to proceed with this solution.
In my example if you click ROI it will draw a rectangle I want the upper and lower X and Y coordinates of the same.
the working fiddle is http://jsfiddle.net/qf6Ub/2/
// references to canvas and context
var oImageBuffer = document.createElement('img');
var oCanvas = document.getElementById("SetupImageCanvas");
var o2DContext = oCanvas.getContext("2d");
// set default context states
o2DContext.lineWidth = 1;
o2DContext.translate(0.50, 0.50); // anti-aliasing trick for sharper lines
// vars to save user drawings
var layers = [];
var currentColor = "black";
// vars for dragging
var bDragging = false;
var startX, startY;
// vars for user-selected status
var $roiCheckbox = document.getElementById("btnROI");
var $layersCheckbox = document.getElementById("btnLAYER");
var $patches = document.getElementById('txtPatchCount');
var $mouse = document.getElementById("MouseCoords");
var roiIsChecked = false;
var layersIsChecked = false;
var patchCount = 0;
// listen for mouse events
oCanvas.addEventListener('mousedown', MouseDownEvent, false);
oCanvas.addEventListener('mouseup', MouseUpEvent, false);
oCanvas.addEventListener('mousemove', MouseMoveEvent, false);
oCanvas.addEventListener('mouseout', MouseOutEvent, false);
$("#txtPatchCount").keyup(function () {
getStatus();
// clear the canvas
o2DContext.clearRect(0, 0, oCanvas.width, oCanvas.height);
// redraw all previously saved line-pairs and roi
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
if (layer.patchCount > 0) {
layer.patchCount = patchCount;
}
draw(layer);
}
});
// mouse event handlers
function MouseDownEvent(e) {
e.preventDefault();
startX = e.clientX - this.offsetLeft;
startY = e.clientY - this.offsetTop;
currentColor = randomColor();
getStatus();
bDragging = true;
}
function MouseUpEvent(e) {
if (!bDragging) {
return;
}
e.preventDefault();
bDragging = false;
mouseX = e.clientX - this.offsetLeft;
mouseY = e.clientY - this.offsetTop;
layers.push({
x1: startX,
y1: startY,
x2: mouseX,
y2: mouseY,
color: currentColor,
drawLayer: layersIsChecked,
patchCount: patchCount,
});
}
function MouseOutEvent(e) {
MouseUpEvent(e);
}
function MouseMoveEvent(e) {
if (!bDragging) {
return;
}
var mouseX = e.clientX - this.offsetLeft;
var mouseY = e.clientY - this.offsetTop;
// clear the canvas
o2DContext.clearRect(0, 0, oCanvas.width, oCanvas.height);
// redraw all previously saved line-pairs and roi
for (var i = 0; i < layers.length; i++) {
draw(layers[i]);
}
// create a temporary layer+roi object
var tempLayer = {
x1: startX,
y1: startY,
x2: mouseX,
y2: mouseY,
color: currentColor,
drawLayer: layersIsChecked,
patchCount: patchCount,
};
// draw the temporary layer+roi object
draw(tempLayer);
// Display the current mouse coordinates.
$mouse.innerHTML = "(" + mouseX + "," + mouseY + ")" + patchCount;
}
function draw(layer) {
if (layer.drawLayer) {
// set context state
o2DContext.lineWidth = 0.50;
o2DContext.strokeStyle = layer.color;
// draw parallel lines
hline(layer.y1);
hline(layer.y2);
}
if (layer.patchCount > 0) {
// set context state
o2DContext.lineWidth = 1.5;
o2DContext.strokeStyle = '#0F0';
// draw regions
o2DContext.strokeRect(layer.x1, layer.y1, (layer.x2 - layer.x1), (layer.y2 - layer.y1));
var w = layer.x2 - layer.x1;
o2DContext.beginPath();
for (var i = 1; i < layer.patchCount; i++) {
var x = layer.x1 + i * w / layer.patchCount;
o2DContext.moveTo(x, layer.y1);
o2DContext.lineTo(x, layer.y2);
}
o2DContext.stroke();
}
}
function getStatus() {
roiIsChecked = $roiCheckbox.checked;
layersIsChecked = $layersCheckbox.checked;
patchCount = $patches.value;
if (!roiIsChecked || !patchCount) {
patchCount = 0;
}
}
function randomColor() {
return ('#' + Math.floor(Math.random() * 16777215).toString(16));
}
function hline(y) {
o2DContext.beginPath();
o2DContext.moveTo(0, y);
o2DContext.lineTo(oCanvas.width, y);
o2DContext.stroke();
}
document.getElementById("MouseCoords").innerHTML = "(" + x + "," + y + "); "
+"("+ oPixel.x + "," + oPixel.y + "); "
+"("+ oCanvasRect.left + "," + oCanvasRect.top + ")";
}
Ok, I went back to the drawing board and came up with this FIDDLE.
It provides the dimensions of the div and its location from the top and left of the container.
You can calculate the exact coordinates from those numbers.
JS
var divwidth = $('.coord').width();
var divheight = $('.coord').height();
var pos = $('.coord').offset();
$('#divdimensions').html(divwidth + ',' + divheight);
$('#divposition').html( pos.left + ',' + pos.top );
I need to do an action onclick of a particular (point) or a rectangle in a canvas.
Example:
$(document).ready(function(){
var canvas = $('#myCanvas').get(0);
if (!canvas.getContext) { return; }
var ctx = canvas.getContext('2d');
ctx.fillRect(150,140,8,8);
ctx.fillRect(200,120,8,8);
ctx.fillRect(200,160,8,8);
});
I need to connect two points with a line and another two points with a curve using javascript .How can i do this?
You need to maintain the regions yourselves. There are no objects on a canvas, only pixels and the browser does not know anything about it.
Demo here
You can do something like this (simplified):
// define the regions - common for draw/redraw and check
var rect1 = [150,140,8,8];
var rect2 = [200,120,8,8];
var rect3 = [200,160,8,8];
var regions = [rect1, rect2, rect3];
Now on your init you can use the same array to render all the rectangles:
$(document).ready(function(){
var canvas = $('#myCanvas').get(0);
if (!canvas.getContext) { return; }
var ctx = canvas.getContext('2d');
//use the array also to render the boxes
for (var i = 0, r; r = regions[i]; i++) {
ctx.fillRect(r[0],r[1],r[2],r[3]);
}
});
On the click event you check the array to see if the mouse coordinate (corrected for canvas) is inside any of the rectangles:
$('#myCanvas').on('click', function(e){
var pos = getMousePos(this, e);
// check if we got a hit
for (var i = 0, r; r = regions[i]; i++) {
if (pos.x >= r[0] && pos.x <= (r[0] + r[2]) &&
pos.y >= r[1] && pos.y <= (r[1] + r[3])) {
alert('Region ' + i + ' was hit');
}
}
});
//get mouse position relative to canvas
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
Also remember to redraw the canvas if the window is re-sized or for other reason clears the canvas (browser dialogs etc.).
To connect the boxes you need to store the first hit position and when you get a second hit draw a line between them.
Demo with lines here
Add to the global vars and also make canvas and context available from global (see fiddle for related modifications in onready):
var x1 = -1, y1;
var canvas = myCanvas;
var ctx = canvas.getContext('2d');
And in the click event:
$('#myCanvas').on('click', function(e){
var pos = getMousePos(this, e);
for (var i = 0, r; r = regions[i]; i++) {
if (pos.x >= r[0] && pos.x <= (r[0] + r[2]) &&
pos.y >= r[1] && pos.y <= (r[1] + r[3])) {
//first hit? then store the coords
if (x1 === -1) {
x1 = pos.x;
y1 = pos.y;
} else {
//draw line from first point to this
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
x1 = -1; //reset (or keep if you want continuous lines).
};
}
}
});
I'm having trouble trying to make an animation with JavaScript and the HTML5 canvas element.
I need to have an animation that starts in the bottom right corner of my canvas, which moves up diagonally to the top right hand corner and then reverses back the other direction to create a back and forth movement.
I can get my animation to move diagonally, but then I can't get it to change the direction.
I'm also having trouble getting the animation to start from the bottom no matter what I do.
The code below currently moves my animation top to bottom diagonally.
var context;
var x = 0;
var y = 0;
var stepx = 1.55;
var stepy = 1.55;
function setupAnimCanvas() {
var canvas = document.getElementById('assignmenttwoCanvas');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
setInterval('draw();', 20);
img = new Image();
img.src = '../images/dragon.png';
//animation();
}
}
startPos = (500, 500);
endPos = (0, 0);
function draw() {
ctx.clearRect(0,0, 500,500);
drawBackground();
ctx.drawImage(img, y, x);
x += 3;
if(x < endPos){
x -= stepx;
y += stepy;
}
else if (y > endPos) {
x += stepx;
y -= stepy;
}
else {
endPos = startPos;startPos = y;
}
moveit();
setTimeout('mover()',25);
}
You can use a delta value for x and y. When the x or y position is at start or end you just reverse the delta by setting delta = -delta;
var dx = -3, dy = -3;
Then simply check for any criteria that would reverse the direction:
if (x < endPos[0] || x > startPos[0] || y < endPos[1] || y > startPos[1] ) {
dx = -dx;
dy = -dy;
}
See demo here:
http://jsfiddle.net/AbdiasSoftware/5dSSZ/
The essence of this (see comments and original source lines at fiddler-link)
var startPos = [500, 500];
var endPos = [0, 0];
var dx = -3, dy = -3;
var x = startPos[0], y = startPos[1];
function draw() {
ctx.clearRect(0, 0, 500, 500);
ctx.fillRect(x, y, 20, 20); //for demo as no image
x += dx;
y += dy;
if (x < endPos[0] || x > startPos[0] ||
y < endPos[1] || y > startPos[1] ) {
dx = -dx;
dy = -dy;
}
setTimeout(draw, 16); //requestAnimationFrame is a better choice
}
So ... I created canvas element with jquery:
var canvasElement = $("<canvas id='map' width='" + CANVAS_WIDTH + "' height='" + CANVAS_HEIGHT + "'></canvas");
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo('body');
And now i want to get mouse coordinates, but the next code doesn't work:
canvasElement.onmousemove = mousemove;
function mousemove(evt) {
var mouseX = evt.pageX - canvasElement.offsetLeft;
var mouseY = evt.pageY - canvasElement.offsetTop;
alert(mouseX+":"+mouseY);
}
canvasElement.offsetLeft is not work, evt.pageX too... Help !
Those properties aren't cross-browser.
I know of two solutions to get the canvas position :
the easy one : use jQuery offset
another one : use a custom and complex code :
if (!canvasElement.offsetX) {
// firefox
var obj = canvasElement;
var oX = obj.offsetLeft;var oY = obj.offsetTop;
while(obj.parentNode){
oX=oX+obj.parentNode.offsetLeft;
oY=oY+obj.parentNode.offsetTop;
if(obj==document.getElementsByTagName('body')[0]){break}
else{obj=obj.parentNode;}
}
canvas_position_x = oX;
canvas_position_y = oY;
} else {
// chrome
canvas_position_x = canvasElement.offsetX;
canvas_position_y = canvasElement.offsetY;
}
As there is a loop, you'd better store canvas_position_x and canvas_position_y and have them recomputed at each document resize instead of at each mousemove.
Demonstration
Live Demo
Its pretty easy actually without jQuery. Below is the important part from the fiddle. cX and cY are the coordinates of the clicked canvas.
function clicked(e) {
var cX = 0,
cY = 0;
if (event.pageX || event.pageY) {
cX = event.pageX;
cY = event.pageY;
}
else {
cX = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
cY = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
cX -= canvas.offsetLeft;
cY -= canvas.offsetTop;
ctx.fillRect(cX, cY, 2, 2);
}
Demo with mouse move
Is there a simple way to get relative mouse coordinates while moving mouse over HTML5 canvas?
I found this:
function getMousePos(canvas, evt){
// get canvas position
var obj = canvas;
var top = 0;
var left = 0;
while (obj && obj.tagName != 'BODY') {
top += obj.offsetTop;
left += obj.offsetLeft;
obj = obj.offsetParent;
}
// return relative mouse position
var mouseX = evt.clientX - left + window.pageXOffset;
var mouseY = evt.clientY - top + window.pageYOffset;
return {
x: mouseX,
y: mouseY
};
}
But it seems too heavy to me. Is there a reason using frameworks (like Kinetic) when working with canvas to simplify such things?
If you're not using your mousemove on your canvas use this:
$(function () {
canvas = document.getElementById('canvas');
canvas.onmousemove = mousePos;
});
function mousePos(e) {
if (e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if (e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
}
You could position canvas absolutely and then remove while loop.
Ultimately, if canvas would not move, you could cache it's offset and then use cached value.
And to cover all cases: if canvas would have fixed position, you'll need not consider scrolling: pageXOffset, pageYOffset.