toggle image in canvas - javascript

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;
}

Related

Game Collision-detection FIX

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

HTML5 Canvas slider

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();
}
});

How to get a variable into a function from another under "use strict"

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();
});

How to make an array of graphic circles that I can redraw to the screen on intervals?

I want to draw circles on the screen but I want to store them in an array for later use in building a centipede type game. I am somewhat new to object in Javascript.
My object is Circles as below.
function Circles(x,y,r) {
var cX = x;
var cY = y;
var cR = r;
}
I want to create an array of say 50 circles that I can loop through and display to the screen because currently I have a square that moves around the screen that I can control with the left and right keys.
I want to redraw the array to the screen.
**How can I create the array?"
Code:
<script type="text/javascript">
var theCanvas=document.getElementById("myCanvas");
var canvasContext=theCanvas.getContext("2d");
var radX;
var radY;
var radR;
var context;
var numCircle = 50;
var circleArray = new Circles(50);
function Circles(x,y,r) {
var cX = x;
var cY = y;
var cR = r;
}
function clearCanvas() {
//context.clearRect(0,0,WIDTH,HEIGHT);
}
function drawCircle(x,y,r,context) {
context.beginPath();
context.arc(x,y,r,0,Math.PI*2,true);
context.closePath();
context.fill();
}
function getRandomColor() {
// creating a random number between 0 and 255 -- this will set the color of the random sized circle
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
// going from decimal to hex -- converts the int value to a hex for the color
var hexR = r.toString(16);
var hexG = g.toString(16);
var hexB = b.toString(16);
// making sure single character values are prepended with a "0"
if (hexR.length == 1) hexR = "0" + hexR;
if (hexG.length == 1) hexG = "0" + hexG;
if (hexB.length == 1) hexB = "0" + hexB;
// creating the hex value by concatenatening the string values
var hexColor = "#" + hexR + hexG + hexB;
return hexColor.toUpperCase();
}
function drawGameBottomLine() {
canvasContext.beginPath();
canvasContext.moveTo(0,530);
canvasContext.lineTo(450,530);
canvasContext.stroke();
}
function getRandomNum(x,y) {
radX = Math.random()*theCanvas.width;
radY = Math.random()*theCanvas.height;
}
function buildCircle() {
for(var i=0; i<numCircle; i++) {
do {
isDrawable = false;
radX = Math.random()*theCanvas.width;
radY = Math.random()*theCanvas.height;
radR = Math.random()*10+3;
if ((radX>5 && radX<435) && (radY>0 && radY<520)) {
circleArray.x[i] = radX;
circleArray.y[i] = radY;
circleArray.r[i] = radR;
isDrawable = true;
//canvasContext.fillStyle='#123321;'//getRandomColor();
//drawCircle(radX,radY,radR,canvasContext);
}
}
while (isDrawable == false);
}
}
function drawCircle(a) {
for(var i=0; i<numCircle; i++) {
canvasContext.fillStyle='#123321;'
drawCircle(circleArray.x[i],circleArray.y[i],circleArray.r[i],canvasContext);
}
}
drawGameBottomLine();
buildCircle();
drawCircles();
All of the code:
<!DOCTYPE HTML>
<html>
<head>
<style>
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script>
var context;
var rightKey = false;
var leftKey = false;
var upKey = false;
var downKey = false;
var block_x;
var block_y;
var block_h = 10;
var block_w = 10;
function init() {
//canvas = document.getElementById('myCanvas');
context = $('#myCanvas')[0].getContext('2d');
WIDTH = $('#myCanvas').width();
HEIGHT = $('#myCanvas').height();
block_x = WIDTH / 2 - 15;
block_y = HEIGHT /2 - 15;
setInterval('draw()', 25);
}
function clearCanvas() {
//context.clearRect(0,0,WIDTH,HEIGHT);
}
function rect(x,y,w,h) {
context.beginPath();
context.rect(x,y,w,h);
context.endPath();
}
function draw() {
clearCanvas();
if (rightKey)
block_x += 5;
else if (leftKey)
block_x -= 5;
if (upKey)
block_y -= 5;
else if (downKey)
block_y += 5;
if (block_x <= 0)
block_x = 0;
if ((block_x + block_w) >= WIDTH)
block_x = WIDTH - block_w;
if (block_y <= 0)
block_y = 0;
if ((block_y + block_h) >= HEIGHT)
block_y = HEIGHT - block_h;
context.fillRect(block_x,block_y,block_w,block_h);
}
function onKeyDown(evt) {
if (evt.keyCode == 39) rightKey = true;
else if (evt.keyCode == 37) leftKey = true;
if (evt.keyCode == 38) upKey = true;
else if (evt.keyCode == 40) downKey = true;
}
function onKeyUp(evt) {
if (evt.keyCode == 39) rightKey = false;
else if (evt.keyCode == 37) leftKey = false;
if (evt.keyCode == 38) upKey = false;
else if (evt.keyCode == 40) downKey = false;
}
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
</script>
</head>
<body onload="init();">
<canvas id="myCanvas" width="450" height="610" style="border:3px solid #c3c3c3;">
It appears that your browser does not support HTML5 and the canvas element.
</canvas>
<script type="text/javascript">
var theCanvas=document.getElementById("myCanvas");
var canvasContext=theCanvas.getContext("2d");
var radX;
var radY;
var radR;
var context;
var numCircle = 50;
var circleArray = new Circles(50);
function Circles(x,y,r) {
var cX = x;
var cY = y;
var cR = r;
}
function clearCanvas() {
//context.clearRect(0,0,WIDTH,HEIGHT);
}
function drawCircle(x,y,r,context) {
context.beginPath();
context.arc(x,y,r,0,Math.PI*2,true);
context.closePath();
context.fill();
}
function getRandomColor() {
// creating a random number between 0 and 255 -- this will set the color of the random sized circle
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
// going from decimal to hex -- converts the int value to a hex for the color
var hexR = r.toString(16);
var hexG = g.toString(16);
var hexB = b.toString(16);
// making sure single character values are prepended with a "0"
if (hexR.length == 1) hexR = "0" + hexR;
if (hexG.length == 1) hexG = "0" + hexG;
if (hexB.length == 1) hexB = "0" + hexB;
// creating the hex value by concatenatening the string values
var hexColor = "#" + hexR + hexG + hexB;
return hexColor.toUpperCase();
}
function drawGameBottomLine() {
canvasContext.beginPath();
canvasContext.moveTo(0,530);
canvasContext.lineTo(450,530);
canvasContext.stroke();
}
function getRandomNum(x,y) {
radX = Math.random()*theCanvas.width;
radY = Math.random()*theCanvas.height;
}
function buildCircle() {
for(var i=0; i<numCircle; i++) {
do {
isDrawable = false;
radX = Math.random()*theCanvas.width;
radY = Math.random()*theCanvas.height;
radR = Math.random()*10+3;
if ((radX>5 && radX<435) && (radY>0 && radY<520)) {
circleArray.x[i] = radX;
circleArray.y[i] = radY;
circleArray.r[i] = radR;
isDrawable = true;
//canvasContext.fillStyle='#123321;'//getRandomColor();
//drawCircle(radX,radY,radR,canvasContext);
}
}
while (isDrawable == false);
}
}
function drawCircle(a) {
for(var i=0; i<numCircle; i++) {
canvasContext.fillStyle='#123321;'
drawCircle(circleArray.x[i],circleArray.y[i],circleArray.r[i],canvasContext);
}
}
drawGameBottomLine();
buildCircle();
drawCircles();
</script>
</body>
</html>
It's really pretty simple. You just create an array with something like:
var anArray = [];
and then add objects to it:
anArray.push(object)
You might change your definition of a Circle to a simple factory function. Something like this would make everything pretty easy:
function Circle(x, y, r){
this.x = x;
this.y = y;
this.r = r;
}
// create an array
var anArray = [];
// make a circle instance
var aCircle = new Circle(100, 100, 20)
// you can now access the circle properties like this
aCircle.x
//add it to the array
anArray.push(aCircle)
//now this works too (the x coordinate of the first circle in the array):
anArray[0].x
I've added a fiddle with a working example pared down to the essentials: http://jsfiddle.net/markm/jxeh0kks/
You have a few errors in your code. The big one is that to access the objects in the array you need to specify the index of the array first.
//Don't do this:
circleArray.x[i] = radX;
// Do this:
circleArray[i].x = radX;

Drag and lock inside of the parent

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;
}

Categories

Resources