Online sample http://jsfiddle.net/dhCLd/
A simple drag magnify,
(function($) {
$.fn.drag = function(opt) {
opt = $.extend({
handle: "",
cursor:"move"}, opt);
if(opt.handle === "") {
var $el = this;
} else {
var $el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
if(opt.handle === "") {
var $drag = $(this).addClass('draggable');
} else {
var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
native_width = 0,
native_height = 0;
$drag.css('z-index', 1000).parents('.magnify').on("mousemove", function(e) {
if(!native_width && !native_height){
var image_object = new Image();
image_object.src = $(".small").attr("src");
native_width = image_object.width;
native_height = image_object.height;
}else{
var magnify_offset = $drag.parents('.magnify').offset();
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
var rx = Math.round(mx/$(".small").width()*native_width - $drag.width()/2)*-1;
var ry = Math.round(my/$(".small").height()*native_height - $drag.height()/2)*-1;
var px = mx - $(".large").width()/2;
var py = my - $(".large").height()/2;
var bgp = rx + "px " + ry + "px";
$('.draggable').css({left:px, top:py, backgroundPosition: bgp}).on("mouseup", function() {
$(this).removeClass('draggable').css('z-index', z_idx);
});
}
});
e.preventDefault();
}).on("mouseup", function() {
if(opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
}
})(jQuery);
How can I make the "magnify" stops at the edges around the .small` image, if outside of the image then undraggable. If someone could help?
You can just limit the values of mx (in range [0,magnify's width]) and my (in range [0, magnify's height]):
var magnify = $drag.closest('.magnify');
var magnify_offset = magnify.offset();
var mx = Math.min(Math.max(e.pageX - magnify_offset.left,0),magnify.width());
var my = Math.min(Math.max(e.pageY - magnify_offset.top,0), magnify.height());
Updated demo.
To make the magnifying glass undraggable when it's outside a bounded area, simply test the position of the background image as it is being drag:
var cH = 175/2; //Half of the magnifying glass
if(rx > cH|| ry > cH || rx < -579 + cH || ry < -1107 + cH){ //579 and 1107 are the dimension of the background image
$(this).trigger("mouseup"); //Make it undraggable
return false;
}
Related
I am making a game where it's about clicking on the nearest yellow dot from the green dot.
I got a list named dots.
You can check out my codepen to see the code I'm using.
My problem is that when you're playing the game, sometimes some of the yellow dots are too close to each other. So I am thinking if it's possible to make a collision-detection or something else, to check if the yellow dots collides?
Here is a picture of my game...
I made a red circle around the problem:
The link to my codepen project: /lolkie02/pen/PJVOdy?editors=0010
If you wanna try the game, it only works through iPhone or Android browser since I made the buttons etc. 'touchstart' in the javascript.
function getDistance(obj1, obj2) {
return Math.floor(
Math.sqrt(Math.pow(obj1.cx - obj2.cx, 2) + Math.pow(obj1.cy - obj2.cy, 2))
);
}
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function comparator(a, b) {
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
function difference(source, toRemove) {
return source.filter(function(value) {
return toRemove.indexOf(value) == -1;
});
}
////////////////
// global vars
////////////////
var svg = document.getElementById("svg");
var dotMatrix = document.createElementNS(
"http://www.w3.org/2000/svg",
"circle"
);
var lineMatrix = document.createElementNS("http://www.w3.org/2000/svg", "line");
var screenW = window.innerWidth;
var screenH = window.innerHeight;
var totalDist = document.getElementById("distance");
////////////////
// line constructor
////////////////
function Line(x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.el = document.createElementNS("http://www.w3.org/2000/svg", "line");
this.class = "line";
this.update = function(x1, y1, x2, y2) {
this.el.setAttribute("x1", x1 || this.x1);
this.el.setAttribute("y1", y1 || this.y1);
this.el.setAttribute("x2", x2 || this.x2);
this.el.setAttribute("y2", y2 || this.y2);
this.setAttr("class", this.class);
};
this.setAttr = function(attr, value) {
this.el.setAttribute(attr, value);
};
this.append = function() {
svg.insertBefore(this.el, svg.firstChild);
};
}
////////////////
// dot constructor
////////////////
function Dot(r, cx, cy) {
this.r = r;
this.cx = cx;
this.cy = cy;
this.el = document.createElementNS("http://www.w3.org/2000/svg", "circle");
this.class = "dot";
this.update = function() {
this.el.setAttribute("r", this.r);
this.el.setAttribute("cx", this.cx);
this.el.setAttribute("cy", this.cy);
this.setAttr("class", this.class);
};
// activates a dot
this.activate = function() {
for (i = 0; i < dots.num; i++) {
dots.list[i].setAttr("data-selected", "false");
}
this.setAttr("data-selected", "true");
};
this.visited = function() {
this.setAttr("data-visited", "true");
};
// sets attribute to element
this.setAttr = function(attr, value) {
this.el.setAttribute(attr, value);
};
// gets attribute to element
this.getAttr = function(attr) {
return this.el.getAttribute(attr);
};
// appends element to svg and attaches event listeners
this.append = function() {
svg.appendChild(this.el);
this.el.addEventListener("touchstart", this.onClick);
};
// on click on element
this.onClick = function(event) {
//gets the id and the coords of the dot
var thisId = Number(event.target.getAttribute("data-id").substr(3, 2));
var thisCx = dots.list[thisId].cx;
var thisCy = dots.list[thisId].cy;
// calculates the distance between dots
var distances = [];
for (i = 0; i < dots.num; i++) {
distances[i] = [i, getDistance(dots.selected, dots.list[i])];
}
distances.sort(comparator);
distances.splice(0, 1);
var distancesLeft = [];
for (i = 0; i < distances.length; i++) {
if (dots.left.includes(distances[i][0])) {
distancesLeft.push(distances[i][0]);
}
}
//if the element is the nearest
if (thisId == distancesLeft[0] && dots.left.includes(thisId)) {
// calculates distances
var newDistance = getDistance(dots.list[thisId], dots.selected);
app.score.update(1); // punteggio x numero di poi
// app.score.update(newDistance); punteggio x distanza
//sets the active class to the selected dot
dots.list[thisId].activate();
dots.list[thisId].visited();
// creates the line
lines.list.push(
new Line(
dots.selected.cx,
dots.selected.cy,
dots.list[thisId].cx,
dots.list[thisId].cy
)
);
lines.list[lines.list.length - 1].update();
lines.list[lines.list.length - 1].append();
// creates the preview line
//TODO: eliminare le vecchie preline che rimangono vive
svg.addEventListener("mousemove", function prelineMove(e) {
mouseX = e.pageX;
mouseY = e.pageY;
app.preline.update(thisCx, thisCy, mouseX, mouseY);
});
//saves the selected dots coordinates
dots.selected.id = thisId;
dots.selected.cx = thisCx;
dots.selected.cy = thisCy;
//removes the dot from the list of remaining dots
for (i = 0; i < dots.left.length; i++) {
if (dots.left[i] === thisId) {
dots.left.splice(i, 1);
}
}
if (dots.left.length == 0) {
app.end(true);
}
} else {
app.end(false);
}
};
}
////////////////
// lines group
////////////////
var lines = {
list: []
};
////////////////
// dots group
////////////////
var dots = {};
dots.num = 20;
dots.list = [];
dots.start = 0;
dots.selected = {};
dots.selected.id = dots.start;
dots.left = [];
dots.preline;
////////////////
// app
////////////////
var app = {};
app.level = 2;
app.score = {};
app.score.number = 0;
app.score.el = document.getElementById("score");
app.score.update = function(score) {
app.score.number += score;
app.score.el.textContent = app.score.number;
};
app.score.reset = function() {
app.score.number = 0;
app.score.update(0);
};
app.results = function(points) {
if (points == "reset") {
sessionStorage.setItem("results", 0);
} else {
if (!sessionStorage.getItem("results")) {
sessionStorage.setItem("results", points);
} else {
var newscore = points;
sessionStorage.setItem("results", newscore);
}
}
};
app.launchScreen = function(lastScore, title, description, btnText) {
app.launchScreen.el = document.getElementById("launch-screen");
app.launchScreen.el.setAttribute("class", "is-visible");
var launchScreenTitle = document.getElementById("launch-screen__title");
launchScreenTitle.textContent = title;
var launchScreenDescription = document.getElementById(
"launch-screen__description"
);
launchScreenDescription.textContent = description;
app.launchScreen.btn = document.getElementById("start-btn");
app.launchScreen.btn.textContent = btnText;
app.launchScreen.btn.addEventListener("touchstart", function lauch() {
app.launchScreen.el.setAttribute("class", "");
app.start(app.level);
document.getElementById("score2").style.display = "block";
app.launchScreen.btn.removeEventListener("touchstart", lauch);
});
};
app.preline = new Line(0, 0, 200, 200);
app.preline.setAttr("id", "preline");
app.start = function(dotsNum) {
dots.num = dotsNum;
for (i = 0; i < dots.num; i++) {
var cx = getRandomArbitrary(45, screenW - 45);
var cy = getRandomArbitrary(45, screenH - 45);
dots.list[i] = new Dot(14, cx, cy);
dots.list[i].setAttr("data-id", "id-" + i);
dots.list[i].setAttr(
"style",
"animation-delay:" + i / 10 + "s; transform-origin: " + cx + 'px ' + cy + 'px;');
dots.list[i].update();
dots.list[i].append();
dots.left.push(i);
if (i == dots.start) {
dots.selected.cx = dots.list[dots.start].cx;
dots.selected.cy = dots.list[dots.start].cy;
dots.list[dots.start].setAttr("class", "dot dot--starting");
dots.left.splice(i, 1);
}
// adds the preline
app.preline.update(
dots.selected.cx,
dots.selected.cy,
dots.selected.cx,
dots.selected.cy
);
app.preline.append();
svg.addEventListener("mousemove", function prelineMove(e) {
mouseX = e.pageX;
mouseY = e.pageY;
app.preline.update(dots.selected.cx, dots.selected.cy, mouseX, mouseY);
});
}
// sets starting point
dots.list[dots.start].setAttr("data-selected", "true");
};
app.end = function(win) {
if (win) {
app.level += 2;
app.results(app.score.number);
} else {
app.level = 2;
}
dots.list = [];
dots.selected = {};
dots.left.length = 0;
svg.innerHTML = "";
if (win) {
app.launchScreen(
app.score.number,
"", //"Sådan!",
"", //"Din score er nu: " + sessionStorage.getItem("results") + ' Det næste level vil blive endnu hårdere.',
"NÆSTE LEVEL"
);
} else {
app.launchScreen(
0,
"", //"ARGH!",
"", //"Din endelige score blev: " + sessionStorage.getItem("results"),
"PRØV IGEN"
);
app.results("reset");
app.score.reset();
var score2 = document.getElementById('score2');
var number = score2.innerHTML;
number = 0;
score2.innerHTML = number;
document.getElementById("score2").style.display = "none";
}
};
app.launchScreen(
0,
"STIFINDER",
"Find den tætteste gule prik",
"SPIL"
);
$('.btn').on('touchstart',function(e,data) {
var score2 = document.getElementById('score2');
var number = score2.innerHTML;
number++;
score2.innerHTML = number;
});
Use Pythagorean theorem to determine whether the distance of the centers of two dots are closer (or equal) to the sum of their radii - in that case you have collision.
My answer to the similar question :https://stackoverflow.com/a/46973584/4154250
Trying to create a slider class that lets you easily and quickly customize values. You can drag the handle or click on any part of the slider to move the handle there, and it works... sort of. You can click as many times as you want, but... if you even click once or if you drag, then let go and try again, it only goes down (never up) a tiny bit. That probably sounds confusing, so here's the fiddle.
var Slider = createEntity({
init: function (args) {
args = args || {};
this.x = args.x || 0;
this.y = args.y || 0;
this.width = args.width || 10;
this.height = args.height || 100;
this.min = args.min || 0;
this.max = args.max || 100;
this.value = args.value || 50;
this.rotation = args.rotation || 0;
this.on = args.on || function () {};
var backFill = randHsla();
args.back = args.back || {};
this.back = args.back;
args.back.fill = args.back.fill || backFill;
this.back.fill = args.back.fill;
args.back.borderFill = args.back.borderFill || backFill;
this.back.borderFill = args.back.borderFill;
args.back.width = args.back.width || 5;
this.back.width = args.back.width;
args.back.x = args.back.x || this.width / 2 - this.back.width / 2;
this.back.x = args.back.x;
var handleColor = randHsla();
args.handle = args.handle || {};
this.handle = args.handle;
args.handle.fill = args.handle.fill || handleColor;
this.handle.fill = args.handle.fill;
args.handle.borderStroke = args.handle.borderStroke || handleColor;
this.handle.borderStroke = args.handle.borderStroke;
args.handle.height = args.handle.height || 5;
this.handle.height = args.handle.height;
args.handle.y = args.handle.y || 0;
this.handle.y = args.handle.y;
this.updatePos();
},
draw: function (fx) {
fx.save();
fx.translate(this.x, this.y);
fx.rotate(this.rotation);
fx.fillStyle = this.back.fill;
fx.beginPath();
fx.fillRect(this.back.x, 0, this.back.width, this.height);
fx.closePath();
fx.fillStyle = this.handle.fill;
fx.strokeStyle = this.handle.borderStroke;
fx.beginPath();
fx.rect(0, this.handle.y, this.width, this.handle.height);
fx.closePath();
fx.fill();
fx.stroke();
fx.restore();
},
updateVal: function () {
var oldVal = this.value,
handleRange = this.height - this.handle.height,
valRange = this.max - this.min;
this.value = (handleRange - this.handle.y) / handleRange * valRange + this.min;
if (this.on instanceof Function && this.value !== oldVal) {
this.on();
}
return this;
},
updatePos: function () {
var handleRange = this.height - this.handle.height,
valRange = this.max - this.min;
this.handle.y = handleRange - ((this.value - this.min) / valRange) * handleRange;
return this;
},
getMouse: function (map) {
var self = this,
mouse = getMouse(map),
bounds = {};
setBounds();
map.addEventListener('mousedown', function (event) {
if (hasPoint(bounds, mouse.x, mouse.y)) {
map.addEventListener('mousemove', onMouseMove);
map.addEventListener('mouseup', onMouseUp);
} else if (hasPoint(self, mouse.x, mouse.y)) {
var y = mouse.y - self.y;
self.handle.y = Math.min(self.height - self.handle.height, Math.max(y, 0));
self.updateVal();
}
});
function onMouseUp(event) {
map.removeEventListener('mousemove', onMouseMove, false);
map.removeEventListener('mouseup', onMouseUp, false);
}
function onMouseMove(event) {
var y = mouse.y - self.y;
self.handle.y = Math.min(self.height - self.handle.height, Math.max(y, 0));
self.updateVal();
}
function setBounds() {
bounds.x = self.x;
bounds.y = self.y + self.handle.y;
bounds.width = self.width;
bounds.height = self.handle.height;
}
return this;
}
});
External functions such as createEntity and hasPoint can be found here.
How would I make it work after clicking the slider and letting go after the first?
Add the event listeners if the user clicks on the handle as well, to enable dragging.
map.addEventListener('mousedown', function(event) {
if (hasPoint(bounds, mouse.x, mouse.y)) {
map.addEventListener('mousemove', onMouseMove);
map.addEventListener('mouseup', onMouseUp);
} else if (hasPoint(self, mouse.x, mouse.y)) {
map.addEventListener('mousemove', onMouseMove);
map.addEventListener('mouseup', onMouseUp);
var y = mouse.y - self.y;
self.handle.y = Math.min(self.height - self.handle.height, Math.max(y, 0));
self.updateVal();
}
});
I really don't know how to get the following variable from a function into another function. I've read most of the articles and answers about that, and I think my example is more complex. Otherwise, I'm doing it wrong.
This is the function I'm using to determine the value of the wpbar variable. I even could start with $(document).ready(function(), but I removed it for the example:
function wp_adminbar() {
"use strict";
var win = $(window),
wpbar = 0;
if ($('body').hasClass('admin-bar')) {
win.on("resize load",function(){
var wpbar, w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth;
if (x <= 782) {
wpbar = 46;
} else if (x > 782) {
wpbar = 32;
}
});
}
return wpbar;
}
I want to use the variable wpbar into this another function:
$(document).ready(function($) {
"use strict";
var wpbar = wp_adminbar();
console.log(wpbar); // Returns: 0
});
I'm stuck in that. Edit: Actually, return wpbar; is not working at all.
Edit: Full code of a function contaning the first function. In this case, it works:
$(document).ready(function($) {
"use strict";
var win = $(window),
nav_fixed = $('.enable-fixed'),
header = $('#header-v1');
if (!nav_fixed.length || !header.length) return;
// WordPress Toolbar
var wpbar = 0;
if ($('body').hasClass('admin-bar')) {
win.on("resize load",function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth;
if (x <= 782) {
wpbar = 46;
} else if (x > 782) {
wpbar = 32;
}
});
}
var max_h = 89,
min_h = 55,
var_h = max_h - min_h,
menu = $('.sticky-wrapper-v1, #header-v1, #header-v1 .wrap, #header-v1 .menuwrap ul:first-child > li > a, #header-v1 .main-nav-search a'),
logo = $('#header-v1 #logo, #header-v1 #logo img'),
nav = $('#navigation'),
set_height = function(){
var st = win.scrollTop() + wpbar,
new_h = 0,
new_p = 0,
wrapper = $('.sticky-wrapper-v1'),
top_p = wrapper.offset().top;
if (st <= top_p) {
new_h = max_h;
new_p = 0;
} else if (st <= (top_p + var_h)) {
new_h = max_h - st + top_p;
new_p = st - top_p;
header.removeClass("header-scrolled");
} else {
new_h = min_h;
new_p = var_h;
header.addClass("header-scrolled");
}
wrapper.css('margin-bottom', new_p);
menu.css({'height': new_h + 'px', 'lineHeight': new_h + 'px'});
logo.css({'maxHeight': new_h + 'px'});
nav.css({'height': new_h + 'px'});
};
win.one("resize",function(){
$(".navbtn").toggle(function() {
set_height;
}, function () {
set_height;
});
set_height;
});
win.on('debouncedresize', function(){
max_h = $(menu).attr('style',"").filter(':first').height();
set_height();
});
win.on('scroll', function(){
window.requestAnimationFrame( set_height );
});
set_height();
});
I am trying to drag the object in orthographic camera view. When I start dragging object jumps and mouse pointer comes to center of object then it start dragging normally, but mouse point remains at center. I want mouse pointer should be there where I place at start and it drag object.
So I want when moving a model in the orthogonal views using the cursor, the center of the object is moved to the cursor at the moment.
I would like to be able to select anywhere on a model, without the center jumping to the cursor. Here is my code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Running this will allow you to drag three.js around the screen.
*
* feature requests:
* 1. add rotation?
* 2. axis lock
* 3. inertia dragging
* 4. activate/deactivate? prevent propagation?
*
* #author zz85 from
* follow on http://twitter.com/blurspline
*/
THREE.DragControls = function(_camera, _objects, _domElement, objects) {
if (_objects instanceof THREE.Scene) {
_objects = _objects.children;
}
_objects = objects;
var objectstodrag = new Array();
var _projector = new THREE.Projector();
var _selected;
var me = this;
_offset=new THREE.Vector3();
this.onDocumentMouseMove = function(event) {
var elem = _domElement;
var rect = elem.getBoundingClientRect();
x = (event.clientX - rect.left) / rect.width;
y = (event.clientY - rect.top) / rect.height;
var vector = new THREE.Vector3((x) * 2 - 1, -(y) * 2 + 1, 0.5);
var raycaster = _projector.pickingRay(vector, _camera);
if (_selected) {
var targetPos = raycaster.ray.direction.clone().multiplyScalar(_selected.distance).add(raycaster.ray.origin);
// targetPos.sub(_offset);
var deltax = targetPos.x - _selected.object.position.x;
var deltay = (-targetPos.z) - _selected.object.position.y;
var deltaz = targetPos.y - _selected.object.position.z;
var xenable = true;
var yenable = true;
var zenable = true;
if (selViewMode == "front" || selViewMode == "back") {
yenable = false;
} else if (selViewMode == "right" || selViewMode == "left") {
xenable = false;
} else if (selViewMode == "top" || selViewMode == "bottom") {
zenable = false;
} else {
return;
}
for (var i = 0; i < objectstodrag.length; i++) {
if (xenable == true) {
objectstodrag[i].position.x += deltax;
console.log('xaxis')
// objectstodrag[i].position.x = targetPos.x;
// objectstodrag[i].position.x =objectstodrag[i].position.x /4;
}
if (yenable == true) {
objectstodrag[i].position.y += deltay;
console.log('yaxis')
// objectstodrag[i].position.y = targetPos.z;
// objectstodrag[i].position.y=objectstodrag[i].position.y/4
}
if (zenable == true) {
objectstodrag[i].position.z +=deltaz;
console.log('zaxis')
// objectstodrag[i].position.z = targetPos.y;
// objectstodrag[i].position.z=objectstodrag[i].position.z/4;
}
}
thingiview.updateObjectPostion(_selected.object.geometry);
return 1;
}
var intersects = raycaster.intersectObjects(_objects);
if (intersects.length > 0) {
_domElement.style.cursor = 'pointer';
} else {
_domElement.style.cursor = 'auto';
}
return intersects.length;
}
this.onDocumentMouseDown = function(event) {
// // Do not show cursor move for autonesting in orthogonal views
// if (document.getElementById('autonesting').value == "true" && selViewMode != "iso")
// return;
var elem = _domElement;
var rect = elem.getBoundingClientRect();
x = (event.clientX - rect.left) / rect.width;
y = (event.clientY - rect.top) / rect.height;
var vector = new THREE.Vector3((x) * 2 - 1, -(y) * 2 + 1, 0.5);
var ray = _projector.pickingRay(vector, _camera);
var intersects = ray.intersectObjects(_objects);
if (intersects.length > 0) {
if (intersects[0].object.material.materials[0].color.getHex() == selectedObjectColor)
{
_selected = intersects[0];
_offset.copy(_selected.point).sub(_selected.object.position);
_domElement.style.cursor = 'move';
objectstodrag.splice(0, objectstodrag.length);
objectstodrag = [];
for (var i = 0; i < _objects.length; i++) {
if (_objects[i].geometry.enabled && _objects[i].material.materials[0].color.getHex() == selectedObjectColor) {
objectstodrag.push(_objects[i]);
}
}
} else {
objectstodrag.splice(0, objectstodrag.length);
objectstodrag = [];
}
}
if (me.onHit)
me.onHit(intersects.length > 0);
if (intersects != undefined) {
if (intersects[0] != undefined) {
if (intersects[0].object.material.materials[0].color.getHex() == selectedObjectColor) {
return intersects.length;
}
}
}
return 0;
};
this.onDocumentMouseUp = function(event) {
if (_selected) {
if (document.getElementById("autonesting").value == "false") {
setPositionOnRotationInManualNest(true);
}
if (me.onDragged)
me.onDragged();
_selected = null;
}
_domElement.style.cursor = 'auto';
};
};
This is a start to do assignment for Uni. But for now on I have problem to manage to toggle between images. This is meant to be start for turn around match game. It suppose to be images and words and match them but I have problem so far with this toggle function. I have this code so far:
var myButton = new Image();
var mouseX = 0;
var mouseY = 0;
var backgroundImage = new Image();
var nothing = "num/w/2.png";
var something = "num/w/3.png";
function drawButton(buttonObj)
{
canvasContext.drawImage(buttonObj, buttonObj.x, buttonObj.y);
}
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY)
{
if(((mouseX > buttonObj.x) && (mouseX < (buttonObj.x + buttonObj.width))) && ((mouseY > buttonObj.y) && (mouseY < (buttonObj.y + buttonObj.height))))
{return true;}
else
{return false;}
}
$(function() {
var canvas = $("#canvas").get(0);
canvasContext = canvas.getContext('2d');
backgroundImage.src = "num/back.jpg";
$(backgroundImage).load(function() {
canvasContext.drawImage(backgroundImage, 0, 0);
myButton.x = 100;
myButton.y = 100;
myButton.width = 100;
myButton.height = 100;
myButton.src = something;
drawButton(myButton);
});
$("#canvas").click(function(eventObject) {
mouseX = eventObject.pageX - this.offsetLeft;
mouseY = eventObject.pageY - this.offsetTop;
if(checkIfInsideButtonCoordinates(myButton, mouseX, mouseY))
{
if(myButton.src = something)
{
myButton.src = nothing;
}
else if(myButton.src = nothing)
{
myButton.src = something;
}
drawButton(myButton);
}
});
});
Any idea why?Thank you.
jsfiddle
You need to make your = in the if statements ==.
if (myButton.src == something) {
myButton.src = nothing;
}
else if (myButton.src == nothing) {
myButton.src = something;
}