replacing cursor with image to be used as target in javascript - javascript

I've tried for a couple of weeks to trouble shoot this problem and I've come to a dead end.
as a word of warning I'm very new to coding and I may not be able to understand much.
I'm trying to draw an image at the location of the mouse.
this is my script so far
$(function()
{
var canvas = $('#canvas')[0];
var context = canvas.getContext("2d");
var img = new Image();
img.src = 'cross.png';
function getTopLeft(elm)
{
var x, y = 0;
x = elm.offsetLeft;
y = elm.offsetTop;
elm = elm.offsetParent;
while(elm != null)
{
x = parseInt(x) + parseInt(elm.offsetLeft);
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
return {Top:y, Left: x};
}
canvas.style.cursor = "none";
canvas.addEventListener("mousemove", function (ev)
{
var mouseX = ev.pageX - getTopLeft(canvas).Left;
var mouseY = ev.pageX - getTopLeft(canvas).Top;
});
function animate()
{
context.onmousemove = function(evt)
{
context.clearRect(0,0,canvas.width,canvas.height);
context.drawImage(img, Left, Top);
}
}
});
I think the problem lies in defining the x y value of the picture ive tried every variable used in the code but to no avail the script loads without error but doesnt draw the image at the mouse location.
I have just realised also that i need the image to be centred over the mouse position.

Related

Fixing the canvas offset in Raphael.js when DOM element centered

I'm creating circles in a Raphael.js Canvas with a clicking action. When the canvas is drawn at the origin of the website it works fine. But when I move it to the middle some type offseting happens and only when you click on the right side of the canvas the circles are drawn at the left side of the canvas. Even though I have my listener action to the canvas and not the div that the is append to, here is the code:
<body>
<div id="container"></div>
</body>
Here is the JS:
var canvas = Raphael("container", 500, 500);
var ourCanvas = $('svg').last();
ourCanvas.attr("id", "canvas");
var canvasHandler = $("#canvas");
//We create a div with a class to append our canvas
var containerHandler = $("#container");
var circleClass = $("circle.quincy");
var justDragged = false;
canvasHandler.mouseup(function (e) {
var mouseX = e.pageX;
var mouseY = e.pageY;
makeCircle(mouseX, mouseY);
});
function makeCircle(mouseX, mouseY) {
var radius;
var fill;
var thisCirclesID = String(new Date().getTime());
var circle = canvas.circle(mouseX, mouseY, 50).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5,
});
}
Here is a JSFiddle
I wonder if the way that I'm using the event position is correct. Any suggestion is more than welcome.
Thanks
M
I figured it out after realizing that the offset of the new position of svg was causing the mouse event to not recognize its real position. I found this blog post that shows how to use the offsetParent method to calculate the new position of my canvas relative its parent . Here is the code:
$(document).ready(function () {
//We create our canvas and add an ID
var canvas = Raphael("container", 500, 500);
var ourCanvas = $('svg').last();
ourCanvas.attr("id", "canvas");
var canvasHandler = $("#canvas");
//We create a div with a class to append our canvas
var containerHandler = $("#container");
var circleClass = $("circle.quincy");
var justDragged = false;
canvasHandler.mouseup(function (e) {
var mouseX = e.pageX - findPos(this)[0];
var mouseY = e.pageY - findPos(this)[1];
makeCircle(mouseX, mouseY);
findPos(this);
console.log("This is the position of the mouse in X: " + e.pageX);
console.log("This is the position of the mouse in Y: " + e.pageY);
});
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj == obj.offsetParent);
console.log(curleft);
console.log(curtop);
// return [curleft, curtop];
}
return [curleft, curtop];
}
As you can see the findPos(obj) returns and array of the new position of X and Y. So I substract that to my mouseX and mouseY to get the real position on the svg when clicking.
Update
Doing more reading and asking around. I didn't realize what type of elements the web browser returns. Instead of using e.pageX and e.pageY. offsetX offers the position of the mouse in respect to the parent giving the real coordinates. So the code will look like this:
canvasHandler.mouseup(function (e) {
var mouseX = e.offsetX;
var mouseY = e.offsetY;
makeCircle(mouseX, mouseY);
findPos(this);
});
This makes it easier since the offset takes into consideration the real position of the mouse in respect to the element.

Clicakble planets

Im trying to make planets that give an alert message when clicked.
Problem is, onmousedown only works on canvas, as far I tested.
Code for planets:
var planets = [];
for (var b=0;b<3;b++) {
planets.push(planet(0,360,Math.random()*600,Math.random()*600));
}
function planet(I,shiips,xpos,ypos){
I = I||{};
I.ships = shiips;
I.x=xpos;
I.y=ypos;
return I;
}
code for click detection; tests both for planet object and the image
update = function(){
planetImage.onmousedown=function(){alert("works!")};
planets[0].onmousedown=function(){alert("works!")};
}
setInterval(update,100);
Im using canvas to draw the images, if that hhelps.
I found the following code that gives mouse position, but it doesnt work for me:
(function() {
var mousePos;
window.onmousemove = handleMouseMove;
setInterval(getMousePosition, 100); // setInterval repeats every X ms
function handleMouseMove(event) {
event = event || window.event; // IE-ism
mousePos = {
x: event.clientX,
y: event.clientY
};
}
function getMousePosition() {
var pos = mousePos;
if (!pos) {
// We haven't seen any movement yet
}
else {
// Use pos.x and pox.y
}
}
})();
Im trying to keep it simple, I don't really like jquery or anything complicated.
Once again: the problem is onmousedown only works on the canvas object, i.e.
canvas.onmousedown=function(){alert("works!")};
I got it working now with this code:
update = function(){
canvas.onmousedown=function(){
var e = window.event;
var posX = e.clientX;
var posY = e.clientY;
alert("X position: "+ posX + " Y position: " + posY);
};
setInterval(update,100);

RaphealJS Resize and mouse shift

I have been using RaphealJS to create a vector drawing tool, I have all the drawing completed and working
my issues comes in when I resize the browser window and try to draw the mouse pointer is off from the location that is being drawn.
I use the mouse move event on the browser and draw lines , Like so
$(document).mousemove(function(e){
if (IE) {
var dh = $("#details").height();
var dw = $("#details").width();
xx = e.offsetX;
yy = e.offsetY;
} else {
var offset = $("#workcanvas").offset();
xx = e.pageX - offset.left;
yy = e.pageY - offset.top;
}
if (lineObject != null) {
lineObject.updateEnd(xx, yy);
} else {
lineObject = Line(xx, yy, xx, yy, MasterCanvas);
}
});
I create my canvas and background image
var MasterCanvas = Raphael($("#workcanvas").attr("id"));
var MasterBGImage = MasterCanvas.image(imgPath, 0, 0, $("#workcanvas").width(),$("#workcanvas").height());
MasterCanvas.setViewBox(0, 0, $("#workcanvas").width(), $("#workcanvas").height(), true);
and in my window resize event I tried this
MasterCanvas.setSize($("#workcanvas").width(), $("#workcanvas").height());
Now I have beat my head against this for a few days to no avail. Please note: I can the drawing function work, and as long as the window does not resize every thing is great but when the page resizes the drawing point is off.
Just in case anyone else has this problem, it turns out to be a viewBox problem, I had to calculate the mouse position based on the viewBox coordinates not the screen so my original code becomes:
$(document).mousemove(function(e){
var uupos = MasterCanvas.canvas.createSVGPoint();
uupos.x = e.clientX;
uupos.y = e.clientY;
var ctm = MasterCanvas.canvas.getScreenCTM();
if (ctm = ctm.inverse())
uupos = uupos.matrixTransform(ctm);
x = uupos.x;
y = uupos.y;
if (lineObject != null) {
lineObject.updateEnd(x, y);
} else {
lineObject = Line(x, y, x, y, MasterCanvas);
}
});
Edit:
Looks like this solution is SVG only though and it does not work in IE8 which is a requirement for me - any ideas.
Is there something like viewBox coordinates in VML

Place image on canvas at same x,y position as mouse onclick

I'm trying to make a web app that lets the user insert small images of characters on an html canvas. The plan is to have the user click a button on a virtual keyboard, and then click on the canvas to have the corresponding character appear wherever the user clicked. Right now I'm just trying to get one image to appear on the canvas when clicked, but so far it isn't doing anything. Here's the code I have now, which is embedded in the html file.
<script type="text/javascript">
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
var el = mathCanvas;
var xPos = 0;
var yPos = 0;
while(el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)){
xPos += el.offsetLeft - el.scrollLeft;
yPos += el.offsetTop - el.scrollTop;
el = el.parentNode;
}
var img = new Image();
img.src = "five.png";
mathCanvas.onclick = function(event){
var x = event.clientX - xPos;
var y = event.clientY - yPos;
ctx.drawImage(img,x,y);
};
</script>
I've tested the onclick event, and it returns coords, but the image won't appear. What's going wrong here?
This should work since the click event will be firing on the canvas itself:
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
var img = new Image();
img.src = "five.png";
mathCanvas.onclick = function(event){
var x = event.offsetX;
var y = event.offsetY;
ctx.drawImage(img,x,y);
};
To center the image on the point:
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
var img = new Image();
img.src = "five.png";
mathCanvas.onclick = function(event){
var x = Math.round(event.offsetX - img.width/2);
var y = Math.round(event.offsetY - img.height/2);
ctx.drawImage(img,x,y);
};

Implement dragging an image within a canvas

I want to implement dragging of an image within a canvas. I want simplest code for that. So far I have seen a lot of examples but they have used complex ways of implementation. I want an example that is easy to learn and implement.
It's pretty difficult. You'll first need to write a function that can detect when you click a particular element. However, before we can do that, we must define what we mean by "element". Is it the product of a single draw instruction (e.g. a rectangle or arc), or something complex? (Imagine I wanted to draw a cat and make the entire cat draggable as a unit.)
A canvas is nothing but a collection of pixels. If you want your program to have an idea of "shapes" or even "collections of shapes treated as a unit" you'll need to implement them yourself as data structures external to the canvas itself. Once you have that, you can write an onmousedown handler that takes the x/y point clicked and determine what shape (if any) the click falls inside of (and if it falls inside of multiple shapes, check which has the foremost z-index). Then add an onmousemove handler that erases and redraws the shape on the canvas based on the information in the shape data object.
This is a moderately difficult problem with very difficult prerequisite problems (creating data structures that can describe a wide range of shapes as well as collections of shapes). I highly recommend you use a canvas drawing library that has already solved these problems. I use cake.js but there are loads of options available.
If you don't have to use the HTML5 canvas, jQuery UI is a lot simpler:
HTML:
<img class="drag-me" src="http://www.google.com/images/srpr/logo3w.png">​
JavaScript:
$(function() {
$('.drag-me').draggable();
});
​
See it in action:
http://jsfiddle.net/flackend/TQzSe/
The jQuery UI API has a lot of options too to make it act how you want:
http://jqueryui.com/demos/draggable/
Plus, if it doesn't do what you need, it's easy to implement yourself. Post here if you need help with that.
jsfiddle.net/Zevan/QZejF/5 This may help you.
<html>
<head>
<title>Test Page</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<canvas id="c" width = "500" height = "500" ></canvas>
<script type="text/javascript">
var canvas = $("#c");
var c = canvas[0].getContext("2d");
//var path = "http://wonderfl.net/images/icon/e/ec/ec3c/ec3c37ba9594a7b47f1126b2561efd35df2251bfm";
var path = "blue.jpg";
var path2 = "purple.jpg";
var image1 = new DragImage(path, 200, 100);
var image2 = new DragImage(path2, 300, 100);
var loop = setInterval(function() {
c.fillStyle = "gray";
c.fillRect(0, 0, 500, 500);
image1.update();
image2.update();
}, 30);
var mouseX = 0,
mouseY = 0;
var mousePressed = false;
var dragging = false;
canvas.mousemove(function(e) {
mouseX = e.offsetX;
mouseY = e.offsetY;
})
$(document).mousedown(function() {
mousePressed = true;
}).mouseup(function() {
mousePressed = false;
dragging = false;
});
function DragImage(src, x, y) {
var that = this;
var startX = 0,
startY = 0;
var drag = false;
this.x = x;
this.y = y;
var img = new Image();
img.src = src;
this.update = function() {
if (mousePressed ) {
var left = that.x;
var right = that.x + img.width;
var top = that.y;
var bottom = that.y + img.height;
if (!drag) {
startX = mouseX - that.x;
startY = mouseY - that.y;
}
if (mouseX < right && mouseX > left && mouseY < bottom && mouseY > top) {
if (!dragging){
dragging = true;
drag = true;
}
}
} else {
drag = false;
}
if (drag) {
that.x = mouseX - startX;
that.y = mouseY - startY;
}
c.drawImage(img, that.x, that.y);
}
}
</script>
</body>
</html>

Categories

Resources