I am trying to make a simple point and click game with canvas and i'd like to change the cursor to pointer when i hover on a drawn image and change it back to default when i hover off. So i was trying to make an onhover function for each object on my canvas. Is there any easy way to check if i hover over an image ?
My code looks something like this so far :
//heres an object for my canvas
var cupboard = {
x:200,
y:320,
h:300,
w:180,
imgUrl:"data\\cbc.png",
type:2,
status:'c',
onhover: function(e,canvas)
{
if((e.x >= this.x && e.x <= this.x+this.w) &&(e.y >= this.y && e.y <=
this.y+this.h)){
canvas.style.cursor = "pointer";
}
else
{
canvas.style.cursor = "default";
}
}
//i use an array for these objects
room1[cupboard,silverkey];
//heres the event listener
document.getElementById("mainCanvas").addEventListener("mousemove",
function(evt){
var mousepos = getMousePos(document.getElementById("mainCanvas"),evt);
for(i in room1)
{
(function(m){
room1[m].onhover(mousepos,document.getElementById("mainCanvas"));
})(i);
}
});
I had a look online for a solution and cam across this page :
Add onclick and onmouseover to canvas element
markE's answer is very long but could be useful for you, especially the part about '.isPointInside'.
Hope this helps!
Related
First time posting here, hope I'm doing this right :) I am trying to create a 360 spin in Adobe Animate with createJS, using a sequence of images embedded in a MovieClip. I have managed to get control of the timeline playhead using the code below:-
var start_x;
var startFrame;
var changeDistance;
var travelDistance;
this.threeSixty.addEventListener("mousedown", onMouseDown.bind(this));
this.threeSixty.addEventListener("pressup", onMouseUp.bind(this));
function onMouseDown(e) {
start_x = e.stageX;
startFrame = this.threeSixty.timeline.position;
this.threeSixty.addEventListener("pressmove", onMouseMove.bind(this));
}
function onMouseUp(e) {
this.threeSixty.removeEventListener("pressmove", onMouseMove.bind(this));
}
function onMouseMove(e) {
var changeDistance = e.stageX-start_x;
var travelDistance = startFrame+changeDistance;
if (travelDistance > this.threeSixty.timeline.duration){
this.threeSixty.gotoAndStop(travelDistance % this.threeSixty.timeline.duration);
}else if (travelDistance < 0){
this.threeSixty.gotoAndStop (this.threeSixty.timeline.duration + (travelDistance % threeSixty.timeline.duration));
} else {
this.threeSixty.gotoAndStop(travelDistance);
}
}
The problem is, when you click and drag the image along the X axis, the image sequence only moves forward/backwards by a single frame, as opposed to continuing the image sequence until the either mouse has stopped moving, or the mouse click is released. Any ideas where I might be going wrong here?
Thanks
I have a "ship" that I have drawn on my canvas and I want to be able to drag it left and right on the bottom of the canvas when it is clicked. I have done some research but I'm having no luck.
I'm assuming I use onMouseDown to do this so I have this when the page loads...
canGame.onMouseDown = canCanvas.onMouseDown(e);
and here is the code that creates my ship
gShip = spriteNew("MediumSpringGreen", 230, 950, 150, 20);
From there I am not really sure what to do. I have a gameUpdate function which moves the invaders down the screen. A gameInit function that will draw the invaders and ship on the screen. Also I have a gameDraw function which draws everything on the screen. I have a few others which are not really important for my issue.
Here is the jsfiddle with the full source code. For some reason though it will run on my browser when I run the HTM file but not in jsfiddle.
http://jsfiddle.net/f66bk/2/
Like I said in comment, the best way of doing this kind of behaviour is by using the events mouseup, mousedown and mousemove.
I defined a var named isMouseDown to know that the ship is dragged that I set to true on mousedown and false on mouseup:
canGame.onMouseDown = function() { isMouseDown = true }
canGame.onMouseUp = function() { isMouseDown = false }
You will also need the event onmousemove to get your mouse position to redraw your ship properly:
canGame.onMouseUp = function(event) { moveShip(event, this) }
In the function moveShip, you can get your mouse position and set the position of your ship properly:
function moveShip(evt, obj) {
if(!isMouseDown)
return;
var target = evt.target || evt.srcElement,
rect = target.getBoundingClientRect(),
offsetX = evt.clientX - rect.left;
gShip.Rect.X = offsetX - gShip.Rect.Width/2;
}
Here is your jsfiddle :)
I'm making a small jigsaw like puzzle in html5. Each jigsaw piece is it's own canvas. I need to move the canvas element using the mouse position. I've managed to get the canvas that is clicked, I just need to move it. I tried manipulating the top and left style attributes but the canvas didn't move. Can this be done or am I trying something impossible.
Thanks!
function MouseDown(can, e)
{
MovingCanvas = can;
clicked = true;
}
function MouseMove(e)
{
if(clicked)
{
var mx = e.clientX;
var my = e.clientY;
MovingCanvas.style.top = my;
MovingCanvas.style.left = mx;
}
}
e.clientX and e.clientY are integers.
Styles expect a string of the form {NUMBER}{UNIT}.
You are missing a unit, therefore it won't work.
MovingCanvas.style.top = my+"px";
MovingCanvas.style.left = mx+"px";
Im looking to build a tool to cut out a portion of a photo by letting the user create a closed shape. The user should be able to start drawing lines. From point a to point b, to c, e, d, e, f .... to eventually point a again to close the shape.
I want to use the HTML5 canvas for this. I think this could be a good fit and I'm thinking about using something like flashcanvas as fallback for IE/older browsers?
Is there any tutorial/open source application that I could use to build this sort of thing?
This is the first time I'm going to build an application using HTML5 canvas so are there any pitfalls I should worry about?
I think this is advanced usage of canvas. You have to know the basics, how to draw, how to use layers, how to manipulate pixels. Just ask google for tutorials.
Assuming you know about the previous, I'll give it a try. I've never done that before but I have an idea :
You need 3 canvas :
the one containing your picture (size of your picture)
a layer where the user draw the selection shape (size of your picture, on top of the first canvas)
a result canvas, will contain your cropped picture (same size, this one doesn't need to be displayed)
When the user click on your picture : actually, he clicks on the layer, the layer is cleared and a new line begins.
When he clicks on it another time, the previous started line is drawn and another one begins, etc... You keep doing this until you click on a non-blank pixel (which means you close the shape).
If you want the user to preview the lines, you need another canvas ( explained here http://dev.opera.com/articles/view/html5-canvas-painting/#line )
When the shape is closed, the user has to click inside or outside the shape to determine which part he wants to select. You fill that part with a semi-transparent gray for example ( flood fill explained here http://www.williammalone.com/articles/html5-canvas-javascript-paint-bucket-tool/ )
Now the layer canvas contains a colored shape corresponding to the user selection.
Get the pixel data from your layer and read through the array, every time you find a non-blank pixel at index i, you copy this pixel from your main canvas to the result canvas :
/* First, get pixel data from your 3 canvas into
* layerPixData, resultPixData, picturePixData
*/
// read the entire pixel array
for (var i = 0 ; i < layerPixData.length ; i+=4 ) {
//if the pixel is not blank, ie. it is part of the selected shape
if ( layerPixData[i] != 255 || layerPixData[i+1] != 255 || layerPixData[i+2] != 255 ) {
// copy the data of the picture to the result
resultPixData[i] = picturePixData[i]; //red
resultPixData[i+1] = picturePixData[i+1]; //green
resultPixData[i+2] = picturePixData[i+2]; //blue
resultPixData[i+3] = picturePixData[i+3]; //alpha
// here you can put the pixels of your picture to white if you want
}
}
If you don't know how pixel manipulation works, read this https://developer.mozilla.org/En/HTML/Canvas/Pixel_manipulation_with_canvas
Then, use putImageData to draw the pixels to your result canvas. Job done !
If you want to move lines of your selection, way to go : http://simonsarris.com/blog/225-canvas-selecting-resizing-shape
Here is how you should do that:
The code at the following adds a canvas on top of your page and then by clicking and dragging on that the selection areas would be highlighted. What you need to do after that is to make a screenshot from the underlying page and also a mask layer out of the created image in your canvas and apply that to the screenshot, just like how it is shown in one other answers.
/* sample css code for the canvas
#overlay-canvas {
position: absolute;
top: 0;
left: 0;
background-color: transparent;
opacity: 0.4;
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}
*/
function getHighIndex(selector) {
if (!selector) { selector = "*" };
var elements = document.querySelectorAll(selector) ||
oXmlDom.documentElement.selectNodes(selector);
var ret = 0;
for (var i = 0; i < elements.length; ++i) {
if (deepCss(elements[i],"position") === "static")
continue;
var temp = deepCss(elements[i], "z-index");
if (temp != "auto")
temp = parseInt(temp, 10) || 0;
else
continue;
if (temp > ret)
ret = temp;
}
return ret;
}
maxZIndex = getHighIndex();
$.fn.extend({
lasso: function () {
return this
.mousedown(function (e) {
// left mouse down switches on "capturing mode"
if (e.which === 1 && !$(this).is(".lassoRunning")) {
var point = [e.offsetX, e.offsetY];
$(this).addClass("lassoRunning");
$(this).data("lassoPoints", [point]);
$(this).trigger("lassoStart", [point]);
}
})
.mouseup(function (e) {
// left mouse up ends "capturing mode" + triggers "Done" event
if (e.which === 1 && $(this).is(".lassoRunning")) {
$(this).removeClass("lassoRunning");
$(this).trigger("lassoDone", [$(this).data("lassoPoints")]);
}
})
.mousemove(function (e) {
// mouse move captures co-ordinates + triggers "Point" event
if ($(this).is(".lassoRunning")) {
var point = [e.offsetX, e.offsetY];
$(this).data("lassoPoints").push(point);
$(this).trigger("lassoPoint", [point]);
}
});
}
});
function onLassoSelect() {
// creating canvas for lasso selection
var _canvas = document.createElement('canvas');
_canvas.setAttribute("id", "overlay-canvas");
_canvas.style.zIndex = ++maxZIndex;
_canvas.width = document.width
_canvas.height = document.height
document.body.appendChild(_canvas);
ctx = _canvas.getContext('2d'),
ctx.strokeStyle = '#0000FF';
ctx.lineWidth = 5;
$(_canvas)
.lasso()
.on("lassoStart", function(e, lassoPoint) {
console.log('lasso start');
var pos = lassoPoint;
ctx.beginPath();
ctx.moveTo(pos[0], pos[1]);
console.log(pos);
})
.on("lassoDone", function(e, lassoPoints) {
console.log('lasso done');
var pos = lassoPoints[0];
ctx.lineTo(pos[0], pos[1]);
ctx.fill();
console.log(pos);
})
.bind("lassoPoint", function(e, lassoPoint) {
var pos = lassoPoint;
ctx.lineTo(pos[0], pos[1]);
ctx.fill();
console.log(pos);
});
}
Based on Creating an HTML 5 canvas painting application I created a HTML5 canvas painting application. It works fine, but after creating each object I just need to drag the objects.
Working demo
How to implement drag and drop of the figures?
When the user clicks on the canvas, you have to check the coordinates (compare it to the coordinates for the objects), and see if it's on an object. E.g. You can test if a point (e.g. the coordinates for the mousedown even) is within a circle with this method:
function (pt) {
return Math.pow(pt.x - point.x,2) + Math.pow(pt.y - point.y,2) <
Math.pow(radius,2);
};
If the mousedown is on the object, you have to change the objects coordinates according to how the mouse is moved.
Here is an example, where you can drag a circle:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
drawCircle(circle);
element = document.getElementById('canvas');
element.addEventListener('mousedown', startDragging, false);
element.addEventListener('mousemove', drag, false);
element.addEventListener('mouseup', stopDragging, false);
element.addEventListener('mouseout', stopDragging, false);
}
function mouseX(e) {
return e.clientX - element.offsetLeft;
}
function mouseY(e) {
return e.clientY - element.offsetTop;
}
var Point = function (x, y) {
this.x = x;
this.y = y;
return this;
}
var Circle = function (point, radius) {
this.point = point;
this.radius = radius;
this.isInside = function (pt) {
return Math.pow(pt.x - point.x, 2) + Math.pow(pt.y - point.y, 2) <
Math.pow(radius, 2);
};
return this;
}
function startDragging(e) {
var p = new Point(e.offsetX, e.offsetY);
if(circle.isInside(p)) {
deltaCenter = new Point(p.x - circle.point.x, p.y - circle.point.y);
}
}
function drag(e) {
if(deltaCenter != null) {
circle.point.x = (mouseX(e) - deltaCenter.x);
circle.point.y = (mouseY(e) - deltaCenter.y);
drawCircle(circle);
}
}
function stopDragging(e) {
deltaCenter = null;
}
function drawCircle(circle) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(circle.point.x, circle.point.y, circle.radius, 0, Math.PI*2, true);
ctx.fill();
}
var circle = new Circle(new Point(30, 40), 25);
var deltaCenter = null;
var element;
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300"></canvas>
</body>
</html>
Try it on jsFiddle
The same effect can be accomplished using Raphael.js (http://raphaeljs.com/) with Joint.jS (http://www.jointjs.com/).
Shapes created with Raphael can be accessed like any DOM element and can be manipulated via attributes. It is an awesome framework.
Joint.js helps in connecting the shapes. They also have a diagramming library and can help create ERD, Statemachine and several common diagrams. The best part is that you can extend their diagram element and create your own custom elements. Its jaw-dropingly cool.
Checkout their demos with source code at http://www.jointjs.com/demos
If you are using the raphael as "raw" lib you must handle the undo/redo by yourself.
The graphiti lib did have Undo/Redo Stack inside and supports the export for SVG, PNG, JSON,...
Additional you have some kind of Viso like connectors and ports.
http://www.draw2d.org/graphiti/jsdoc/#!/example
Greetings
I don't think there's an easy way to do this.
If you're just dealing with lines, my approach would be to keep track of all lines created, with starting coordinates, ending coordinates and some kind of z-index. When the user starts a dragging action (onmousedown), you have to check if the point is near the line, and then update the object and redraw the canvas when the mouse is moved.
How can I tell if a point belongs to a certain line?
This gets a lot more complicated if you're dealing with complex objects though. You'll probably have to find a solution to check if a point is inside a path.
Objects drawn into HTML5 Canvas are turned into pixels and then forgotten. You can't adjust properties on them and have the canvas update to see the effects. You can remember them yourself, but the canvas will still have those pixels set, so you'd have to basically redraw the whole canvas (or at least some of it) when you adjust a property.
You might want to consider SVG for this application instead, SVG elements are remembered in the DOM and when their properties are updated the browser will update the graphic to reflect the changes.
If you must use canvas, then you're going to need to write quite a bit of code to handle mouse-hits, object properties, and repaints.