Canvas overlay after creating object - javascript

After drawing a shape, i would like to automaticly create overlay(or just add color to rest of the screen) outside the object (It will be locked so user can create only one shape - as for now i dont know how to code that also)
My code:
<body>
<label class="btn btn--primary" id="btnRoof"><b>Click to draw</b> </label>
<canvas id="canvas" class="canvas" width="800" height="800"></canvas>
<script>
var roof = null;
var roofPoints = [];
var lines = [];
var lineCounter = 0;
var drawingObject = {};
drawingObject.type = "";
drawingObject.background = "";
drawingObject.border = "";
function Point(x, y) {
this.x = x;
this.y = y;
}
$("#btnRoof").click(function () {
if (drawingObject.type == "roof") {
drawingObject.type = "";
lines.forEach(function (value, index, ar) {
canvas.remove(value);
});
//canvas.remove(lines[lineCounter - 1]);
roof = makeRoof(roofPoints);
canvas.add(roof);
canvas.renderAll();
} else {
drawingObject.type = "roof"; // roof type
}
});
// canvas Drawing
var canvas = new fabric.Canvas('canvas');
var x = 0;
var y = 0;
fabric.util.addListener(window, 'dblclick', function () {
drawingObject.type = "";
lines.forEach(function (value, index, ar) {
canvas.remove(value);
});
//canvas.remove(lines[lineCounter - 1]);
roof = makeRoof(roofPoints);
canvas.add(roof);
canvas.renderAll();
console.log("double click");
//clear arrays
roofPoints = [];
lines = [];
lineCounter = 0;
});
canvas.on('mouse:down', function (options) {
if (drawingObject.type == "roof") {
canvas.selection = false;
setStartingPoint(options); // set x,y
roofPoints.push(new Point(x, y));
var points = [x, y, x, y];
lines.push(new fabric.Line(points, {
strokeWidth: 2,
selectable: false,
stroke: 'blue'
}).setOriginX(x).setOriginY(y));
canvas.add(lines[lineCounter]);
lineCounter++;
canvas.on('mouse:up', function (options) {
canvas.selection = true;
});
}
});
canvas.on('mouse:move', function (options) {
if (lines[0] !== null && lines[0] !== undefined && drawingObject.type == "roof") {
setStartingPoint(options);
lines[lineCounter - 1].set({
x2: x,
y2: y
});
canvas.renderAll();
}
});
function setStartingPoint(options) {
var offset = $('#canvas').offset();
x = options.e.pageX - offset.left;
y = options.e.pageY - offset.top;
}
function makeRoof(roofPoints) {
var left = findLeftPaddingForRoof(roofPoints);
var top = findTopPaddingForRoof(roofPoints);
roofPoints.push(new Point(roofPoints[0].x, roofPoints[0].y))
var roof = new fabric.Polyline(roofPoints, {
fill: 'rgba(0,230,64,0.5)',
stroke: 'green',
strokeWidth: 2,
});
roof.set({
left: left,
top: top,
});
return roof;
}
function findTopPaddingForRoof(roofPoints) {
var result = 999999;
for (var f = 0; f < lineCounter; f++) {
if (roofPoints[f].y < result) {
result = roofPoints[f].y;
}
}
return Math.abs(result);
}
function findLeftPaddingForRoof(roofPoints) {
var result = 999999;
for (var i = 0; i < lineCounter; i++) {
if (roofPoints[i].x < result) {
result = roofPoints[i].x;
}
}
return Math.abs(result);
}
</script>
</body>
</html>
For now i can lock shape with doubleclick, but have no idea how to add overlay outside of it.

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

Trying to select lines or rectangles on a canvas

I want to be able to click any line(muscle) and new line then highlight it in my program like I can do with the nodes right now. I want to use context.isPointInPath(), but I feel like that will be too limiting in the fact that the lines are only 1 pixel wide. And now I want to look at changing the lines to rectangles. Because then I would be able to just see if the mouseclick is within the rectangle height and width. But, I'm having trouble finding out a way to connect the rectangle to two nodes like I have it with the strokes right now.
My program so far:
/*jshint esversion: 6 */
//draw everything on canvas
//TODO: Change use of canvas to a container and moving elements around to avoid the buffer of frame drawing
//Node class
class Node {
constructor(x, y, r, color, highlight, highlightColor) {
this.x = x;
this.y = y;
this.r = r || 20;
this.color = color || "#ff0";
this.highlight = highlight || false;
this.highlightColor = highlightColor || "#0000FF";
}
}
//Muscle class
class Muscle {
constructor(node1, node2, width, color) {
this.node1 = node1;
this.node2 = node2;
this.width = width || 5;
this.color = color || "#f00";
//Properties of the nodes this muscle attaches to
Object.defineProperties(this, {
node1x: {
"get": () => this.node1.x,
"set": x => {
this.node1.x = x;
}
},
node1y: {
"get": () => this.node1.y,
"set": y => {
this.node1.y = y;
}
},
node2x: {
"get": () => this.node2.x,
"set": x => {
this.node2.x = x;
}
},
node2y: {
"get": () => this.node2.y,
"set": y => {
this.node2.x = y;
}
}
});
}
}
function setParentForNodes() {
this.nodes.forEach(node => {
node.parentCreature = this;
});
}
class Creature {
constructor(nodes, muscles, nodeColors) {
this.nodes = nodes;
this.muscles = muscles;
this.nodeColors = nodeColors || "#ff0";
setParentForNodes.call(this);
Object.defineProperties(this, {
creatureNumber: {
"get": () => creatures.indexOf(this),
}
});
}
addNewNode(newNode) {
newNode.parentCreature = this;
this.nodes.push(newNode);
}
addNewNodes(newNodes) {
newNodes.forEach(function(node) {
node.parentCreature = this;
}, this);
this.nodes = this.nodes.concat(newNodes);
}
}
var nodes = [
new Node(100, 100),
new Node(200, 200)
];
var muscles = [
new Muscle(nodes[0], nodes[1])
];
var creatures = [
new Creature(nodes, muscles)
];
var addNodePressed = false;
var attachMusclePressed = false;
var addLimbPressed = false;
function draw(container, ctx, nodes, creatureMuscles) {
//draw in the container
ctx.fillStyle = "#000000";
ctx.fillRect(container.y, container.x, container.width, container.height);
// for loop to draw all objects of nodes
for (let i = 0; i < creatures.length; i++) {
var creatureNodes = creatures[i].nodes;
for (let i = 0; i < creatureNodes.length; i++) {
ctx.beginPath();
ctx.arc(creatureNodes[i].x, creatureNodes[i].y, creatureNodes[i].r, 0, 2 * Math.PI);
ctx.fillStyle = creatureNodes[i].color;
ctx.closePath();
ctx.fill();
//check if node needs to be highlighted
if (creatureNodes[i].highlight == true) {
ctx.beginPath();
ctx.arc(creatureNodes[i].x, creatureNodes[i].y, creatureNodes[i].r, 0, 2 * Math.PI);
ctx.strokeStyle = creatureNodes[i].highlightColor;
ctx.lineWidth = 5; // for now
ctx.closePath();
ctx.stroke();
}
}
creatureMuscles = creatures[i].muscles;
//loop and draw every muscle
for (let i = 0; i < creatureMuscles.length; i++) {
ctx.beginPath();
ctx.moveTo(creatureMuscles[i].node1x, creatureMuscles[i].node1y);
ctx.lineTo(creatureMuscles[i].node2x, creatureMuscles[i].node2y);
ctx.strokeStyle = creatureMuscles[i].color;
ctx.lineWidth = creatureMuscles[i].width;
ctx.closePath();
ctx.stroke();
}
}
}
//Handle moving a node with mousedrag
function handleMouseDrag(canvas, creatureNodes) {
var isDrag = false;
var dragNode;
var offset = {
x: 0,
y: 0,
x0: 0,
y0: 0
};
canvas.addEventListener("mousedown", function(e) {
//mousedown then save the position in var x and y
var x = e.offsetX,
y = e.offsetY;
//loop through all the nodes to find the first node that is within radius of the mouse click
for (let i = 0; i < creatures.length; i++) {
var creatureNodes = creatures[i].nodes;
for (let i = 0; i < creatureNodes.length; i++) {
if (Math.pow(x - creatureNodes[i].x, 2) + Math.pow(y - creatureNodes[i].y, 2) < Math.pow(creatureNodes[i].r, 2)) {
isDrag = true;
dragNode = creatureNodes[i];
//offset.x&y = where the node is currently
//offset x0&y0 = where the user clicked
offset = {
x: dragNode.x,
y: dragNode.y,
x0: x,
y0: y
};
return;
}
}
}
});
// when mouse moves and isDrag is true, move the node's position
canvas.addEventListener("mousemove", function(e) {
/*when the user moves the mouse, take the difference of where his mouse is right now and where the user clicked.
Then, add that to where the node is right now to find the correct placement of the node without centering on your mouse
*/
if (isDrag) {
dragNode.x = e.offsetX - offset.x0 + offset.x; // where the mouse is right now - where the user mousedown + where the node is right now
dragNode.y = e.offsetY - offset.y0 + offset.y;
}
});
canvas.addEventListener("mouseup", function(e) {
isDrag = false;
});
canvas.addEventListener("mouseleave", function(e) {
isDrag = false;
});
}
//Handle highlighting and button functionality
function handleMouseClick(canvas, nodes, muscles) {
var highlighted;
var highlightedNode;
canvas.addEventListener("mousedown", function(e) {
var x = e.offsetX,
y = e.offsetY;
var loopbreak = false;
for (let i = 0; i < creatures.length; i++) {
var creatureNodes = creatures[i].nodes;
for (let i = 0; i < creatureNodes.length; i++) {
// check if click is within radius of a node, if it is, highlight and set highlight boolean to true.
if (Math.pow(x - creatureNodes[i].x, 2) + Math.pow(y - creatureNodes[i].y, 2) < Math.pow(creatureNodes[i].r, 2)) {
var clickedNode = creatureNodes[i];
if (addNodePressed) {
console.log("Not valid. Cannot add a node on top of another node.");
loopbreak = true;
break;
} else if (addLimbPressed) {
console.log("Not valid. Cannot add a limb on top of another node.");
loopbreak = true;
break;
} else if (attachMusclePressed) {
if (highlightedNode == clickedNode) {
console.log("Not valid. Cannot attach muscle to the same node.");
loopbreak = true;
break;
} else {
var newMuscle;
if (highlightedNode.parentCreature.creatureNumber == clickedNode.parentCreature.creatureNumber) {
newMuscle = new Muscle(highlightedNode, clickedNode);
highlightedNode.parentCreature.muscles.push(newMuscle);
attachMuscle();
highlightedNode.highlight = false;
highlighted = false;
devTools(true, false, false, false);
} else {
var newNodes = [];
var newMuscles = [];
if (highlightedNode.parentCreature.creatureNumber > clickedNode.parentCreature.creatureNumber) {
highlightedNode.parentCreature.nodes.forEach(function(node) {
newNodes.push(node);
});
highlightedNode.parentCreature.muscles.forEach(function(muscle) {
newMuscles.push(muscle);
});
newMuscle = new Muscle(highlightedNode, clickedNode);
clickedNode.parentCreature.muscles.push(newMuscle);
clickedNode.parentCreature.muscles = clickedNode.parentCreature.muscles.concat(newMuscles);
creatures.splice(creatures.indexOf(highlightedNode.parentCreature), 1);
clickedNode.parentCreature.addNewNodes(newNodes);
} else {
clickedNode.parentCreature.nodes.forEach(function(node) {
newNodes.push(node);
console.log("Clicked node is bigger.");
});
clickedNode.parentCreature.muscles.forEach(function(muscle) {
newMuscles.push(muscle);
});
newMuscle = new Muscle(highlightedNode, clickedNode);
highlightedNode.parentCreature.muscles.push(newMuscle);
highlightedNode.parentCreature.muscles = highlightedNode.parentCreature.muscles.concat(newMuscles);
creatures.splice(creatures.indexOf(clickedNode.parentCreature), 1);
highlightedNode.parentCreature.addNewNodes(newNodes);
}
highlightedNode.highlight = false;
attachMuscle();
devTools(true, false, false, false);
}
}
}
//no button pressed - highlight/unhighlight node
else {
if (highlighted || creatureNodes[i].highlight) {
if (highlightedNode != creatureNodes[i]) {
highlightedNode.highlight = false;
highlightedNode = creatureNodes[i];
highlightedNode.highlight = true;
devTools(false, true, true, true);
} else {
highlightedNode = creatureNodes[i];
highlightedNode.highlight = false;
highlighted = false;
highlightedNode = undefined;
devTools(true, false, false, false);
}
} else {
highlightedNode = creatureNodes[i];
highlightedNode.highlight = true;
highlighted = true;
devTools(false, true, true, true);
}
loopbreak = true;
break;
}
}
}
}
// if click was not in radius of any nodes then check for add limb or create node button press.
if (!loopbreak) {
loopbreak = false;
var newNode;
if (addNodePressed) {
newNode = new Node(x, y);
let newNodes = [];
let newMuscles = [];
newNodes.push(newNode);
var newCreature = new Creature(newNodes, newMuscles);
creatures.push(newCreature);
addNode();
addNodePressed = false;
devTools(true, false, false, false);
} else if (addLimbPressed) {
newNode = new Node(x, y);
let newMuscle = new Muscle(newNode, highlightedNode);
highlightedNode.parentCreature.addNewNode(newNode);
highlightedNode.parentCreature.muscles.push(newMuscle);
addLimb();
addLimbPressed = false;
highlightedNode.highlight = false;
highlighted = false;
highlightedNode = undefined;
devTools(true, false, false, false);
}
}
});
}
//Handle Devtools
function devTools(addNode, removeNode, attachMuscle, addLimb) {
var creatureNumberHTML = document.getElementById("creatureNumber");
var selectedHTML = document.getElementById("selected");
var addNodeB = document.getElementById("addNode");
var removeNodeB = document.getElementById("removeNode");
var attachMuscleB = document.getElementById("attachMuscle");
var addLimbB = document.getElementById("addLimb");
addNodeB.disabled = (addNode) ? false : true;
removeNodeB.disabled = (removeNode) ? false : true;
attachMuscleB.disabled = (attachMuscle) ? false : true;
addLimbB.disabled = (addLimb) ? false : true;
for (let i = 0; i < creatures.length; i++) {
var creatureNumber = i;
var creatureNodes = creatures[i].nodes;
for (let i = 0; i < creatureNodes.length; i++) {
if (creatureNodes[i].highlight == true) {
selectedHTML.innerHTML = `Selected: ${i} node`;
creatureNumberHTML.innerHTML = `Creature number: ${creatureNumber}`;
return;
} else {
creatureNumberHTML.innerHTML = "Creature number: -";
selectedHTML.innerHTML = "Selected: None";
}
}
}
}
//Handle add node button
function addNode() {
var addNodeB = document.getElementById("addNode");
if (addNodePressed) {
addNodePressed = false;
addNodeB.style.background = "";
} else {
addNodePressed = true;
addNodeB.style.backgroundColor = "#808080";
//and unhighlight
}
}
//Handle remove node button
function removeNode() {
for (let i = 0; i < creatures.length; i++) {
var creatureNodes = creatures[i].nodes;
var creatureMuscles = creatures[i].muscles;
for (let i = 0; i < creatureNodes.length; i++) {
if (creatureNodes[i].highlight == true) {
let highlightedNode = creatureNodes[i];
for (let i = 0; i < creatureMuscles.length; i++) {
if (creatureMuscles[i].node1 == highlightedNode || creatureMuscles[i].node2 == highlightedNode) {
creatureMuscles.splice(i, 1);
i--;
}
}
creatureNodes.splice(i, 1);
}
}
}
devTools(true, false, false, false);
}
//Handle attach muscle button
function attachMuscle() {
var attachMuscleB = document.getElementById("attachMuscle");
if (attachMusclePressed) {
attachMusclePressed = false;
attachMuscleB.style.background = "";
} else {
attachMusclePressed = true;
attachMuscleB.style.backgroundColor = "#808080";
}
}
//Handle add limb button
function addLimb() {
var addLimbB = document.getElementById("addLimb");
if (addLimbPressed) {
addLimbPressed = false;
addLimbB.style.background = "";
} else {
addLimbPressed = true;
addLimbB.style.backgroundColor = "#808080";
}
}
//Main - Grabs document elements to draw a canvas on, init node and muscle arrays and then continuously updates frame to redraw
function main() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var container = {
x: 0,
y: 0,
get width() {
return canvas.width;
},
get height() {
return canvas.height;
}
};
handleMouseDrag(canvas, nodes);
handleMouseClick(canvas, nodes, muscles);
// refresh and redraw with new properties in an updateframe infinite loop
function updateFrame() {
ctx.save();
draw(container, ctx, nodes, muscles);
ctx.restore();
requestAnimationFrame(updateFrame);
}
updateFrame();
}
main();
#canvas {
display: block;
}
#info {
display: inline-block;
text-overflow: clip;
overflow: hidden;
margin-right: 200px;
}
#commands {
display: inline-block;
text-align: center;
margin-left: 200px;
}
#devTools {
background-color: aqua;
width: 1500px;
}
section {
width: 200px;
height: 200px;
background-color: grey;
vertical-align: top;
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<!--TODO: Adjust the size of the canvas to fit the window-->
<canvas id="canvas" width="1500" , height="600"></canvas>
<!--TODO: Create buttons for all devtools under the canvas-->
<!--TODO: Make a container for all devtools under the canvas, then add all the functionality to it after-->
<div id="devTools">
<section id="info">
<p>Info</p>
<p id="creatureNumber">Creature Number: -</p>
<p id="selected">Selected: </p>
</section>
<section id="commands">
<p>Commands</p>
<button type="button" id="addNode" onclick="addNode()">Add node</button>
<button type="button" id="removeNode" disabled=true onclick="removeNode()">Remove node</button>
<button type="button" id="attachMuscle" disabled=true onclick="attachMuscle()">Attach muscle</button>
<button type="button" id="addLimb" disabled=true onclick="addLimb()">Add Limb</button>
<div id="muscleLength">
<button type="button" id="increaseLengthB">↑</button>
<p>Muscle Length</p>
<button type="button" id="decreaseLengthB">↓</button>
</div>
</section>
</div>
<script src="scripts/script.js"></script>
</body>
</html>
Another way to solve this is to use a thicker line-width and use isPointInStroke() instead.
var ctx = c.getContext("2d");
var path = new Path2D(); // to store and reuse path
var onLine = false; // state (for demo)
path.moveTo(10, 10); // store a line on path
path.lineTo(200, 100);
ctx.lineWidth = 16; // line width
render(); // initial render
function render() {
ctx.clearRect(0,0,300,150);
ctx.strokeStyle = onLine ? "#09f" : "#000"; // color based on state
ctx.stroke(path); // stroke path
}
c.onmousemove = function(e) { // demo: is mouse on stroke?
onLine = ctx.isPointInStroke(path, e.clientX, e.clientY);
render();
};
body, html {margin:0}
<canvas id=c></canvas>
Note: IE11 does not support the path argument - for it you will need to use ordinary path on the context itself (ctx.moveTo etc.)

How can I animate my background in a loop in node.js

Im making a multiplayer endless runner game and want to make the background move down in a loop with random obstacles in my way. So far I was able to make the scene with controls for the player, have set up a multiplayer aspect, and a sign in. However, I am not able to figure out how to set the background in a loop or add obstacles moving towards the player.
Heres the code:
App2.JS:
var mongojs = require("mongojs");
var db = mongojs('localhost:27017/myGame', ['account','progress']);
var express = require('express');
var app = express();
var serv = require('http').Server(app);
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index2.html');
});
app.use('/client',express.static(__dirname + '/client'));
serv.listen(2000);
console.log("Server started.");
var SOCKET_LIST = {};
var Entity = function(){
var self = {
x:250,
y:250,
spdX:0,
spdY:0,
id:"",
}
self.update = function(){
self.updatePosition();
}
self.updatePosition = function(){
self.x += self.spdX;
self.y += self.spdY;
}
self.getDistance = function(pt){
return Math.sqrt(Math.pow(self.x-pt.x,2) + Math.pow(self.y-pt.y,2));
}
return self;
}
var Player = function(id){
var self = Entity();
self.id = id;
self.number = "" + Math.floor(10 * Math.random());
self.pressingRight = false;
self.pressingLeft = false;
self.pressingUp = false;
self.pressingDown = false;
self.pressingAttack = false;
self.mouseAngle = 0;
self.maxSpd = 25;
self.hp = 10;
self.hpMax = 10;
self.score = 0;
var super_update = self.update;
self.update = function(){
self.updateSpd();
super_update();
if(self.pressingAttack){
self.shootBullet(self.mouseAngle);
}
}
self.shootBullet = function(angle){
var b = Bullet(self.id,angle);
b.x = self.x;
b.y = self.y;
}
self.updateSpd = function(){
if(self.pressingRight && (self.x + 30) < 500)
self.spdX = self.maxSpd;
else if(self.pressingLeft && self.x > 0)
self.spdX = -self.maxSpd;
else
self.spdX = 0;
if(self.pressingUp)
self.spdY = 0;
else if(self.pressingDown)
self.spdY = 0;
else
self.spdY = 0;
}
self.getInitPack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
number:self.number,
hp:self.hp,
hpMax:self.hpMax,
score:self.score,
};
}
self.getUpdatePack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
hp:self.hp,
score:self.score,
}
}
Player.list[id] = self;
initPack.player.push(self.getInitPack());
return self;
}
Player.list = {};
Player.onConnect = function(socket){
var player = Player(socket.id);
socket.on('keyPress',function(data){
if(data.inputId === 'left')
player.pressingLeft = data.state;
else if(data.inputId === 'right')
player.pressingRight = data.state;
else if(data.inputId === 'up')
player.pressingUp = data.state;
else if(data.inputId === 'down')
player.pressingDown = data.state;
else if(data.inputId === 'attack')
player.pressingAttack = data.state;
else if(data.inputId === 'mouseAngle')
player.mouseAngle = data.state;
});
socket.emit('init',{
selfId:socket.id,
player:Player.getAllInitPack(),
bullet:Bullet.getAllInitPack(),
})
}
Player.getAllInitPack = function(){
var players = [];
for(var i in Player.list)
players.push(Player.list[i].getInitPack());
return players;
}
Player.onDisconnect = function(socket){
delete Player.list[socket.id];
removePack.player.push(socket.id);
}
Player.update = function(){
var pack = [];
for(var i in Player.list){
var player = Player.list[i];
player.update();
pack.push(player.getUpdatePack());
}
return pack;
}
var Bullet = function(parent,angle){
var self = Entity();
self.id = Math.random();
self.spdX = Math.cos(angle/180*Math.PI) * 10;
self.spdY = Math.sin(angle/180*Math.PI) * 10;
self.parent = parent;
self.timer = 0;
self.toRemove = false;
var super_update = self.update;
self.update = function(){
if(self.timer++ > 100)
self.toRemove = true;
super_update();
for(var i in Player.list){
var p = Player.list[i];
if(self.getDistance(p) < 32 && self.parent !== p.id){
p.hp -= 1;
if(p.hp <= 0){
var shooter = Player.list[self.parent];
if(shooter)
shooter.score += 1;
p.hp = p.hpMax;
p.x = Math.random() * 500;
p.y = Math.random() * 500;
}
self.toRemove = true;
}
}
}
self.getInitPack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
};
}
self.getUpdatePack = function(){
return {
id:self.id,
x:self.x,
y:self.y,
};
}
Bullet.list[self.id] = self;
initPack.bullet.push(self.getInitPack());
return self;
}
Bullet.list = {};
Bullet.update = function(){
var pack = [];
for(var i in Bullet.list){
var bullet = Bullet.list[i];
bullet.update();
if(bullet.toRemove){
delete Bullet.list[i];
removePack.bullet.push(bullet.id);
} else
pack.push(bullet.getUpdatePack());
}
return pack;
}
Bullet.getAllInitPack = function(){
var bullets = [];
for(var i in Bullet.list)
bullets.push(Bullet.list[i].getInitPack());
return bullets;
}
var DEBUG = true;
var isValidPassword = function(data,cb){
db.account.find({username:data.username,password:data.password},function(err,res){
if(res.length > 0)
cb(true);
else
cb(false);
});
}
var isUsernameTaken = function(data,cb){
db.account.find({username:data.username},function(err,res){
if(res.length > 0)
cb(true);
else
cb(false);
});
}
var addUser = function(data,cb){
db.account.insert({username:data.username,password:data.password},function(err){
cb();
});
}
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
socket.on('signIn',function(data){
isValidPassword(data,function(res){
if(res){
Player.onConnect(socket);
socket.emit('signInResponse',{success:true});
} else {
socket.emit('signInResponse',{success:false});
}
});
});
socket.on('signUp',function(data){
isUsernameTaken(data,function(res){
if(res){
socket.emit('signUpResponse',{success:false});
} else {
addUser(data,function(){
socket.emit('signUpResponse',{success:true});
});
}
});
});
socket.on('disconnect',function(){
delete SOCKET_LIST[socket.id];
Player.onDisconnect(socket);
});
socket.on('sendMsgToServer',function(data){
var playerName = ("" + socket.id).slice(2,7);
for(var i in SOCKET_LIST){
SOCKET_LIST[i].emit('addToChat',playerName + ': ' + data);
}
});
socket.on('evalServer',function(data){
if(!DEBUG)
return;
var res = eval(data);
socket.emit('evalAnswer',res);
});
});
var initPack = {player:[],bullet:[]};
var removePack = {player:[],bullet:[]};
setInterval(function(){
var pack = {
player:Player.update(),
bullet:Bullet.update(),
}
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
socket.emit('init',initPack);
socket.emit('update',pack);
socket.emit('remove',removePack);
}
initPack.player = [];
initPack.bullet = [];
removePack.player = [];
removePack.bullet = [];
},1000/25);
indexCars2.html:
<div id="signDiv">
Username: <input id="signDiv-username" type="text"></input><br>
Password: <input id="signDiv-password" type="password"></input>
<button id="signDiv-signIn">Sign In</button>
<button id="signDiv-signUp">Sign Up</button>
</div>
<div id="animate"
style = "position: relative;"
style = "border: 1px solid green;"
style = "background: yellow; "
style = "width: 100;"
style = "height: 100;"
style = "z-index: 5;">
Sample
</div>
<div id="gameDiv" style="display:none;">
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<div id="chat-text" style="width:500px;height:100px;overflow-y:scroll">
<div>Hello!</div>
</div>
<form id="chat-form">
<input id="chat-input" type="text" style="width:500px"></input>
</form>
</div>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(e) {
var width = "+=" + $(document).width();
$("#animate").animate({
left: width
}, 5000, function() {
// Animation complete.
});
});</script>
<script>
// var WIDTH = 500;
// var HEIGHT = 500;
var socket = io();
//sign
var signDiv = document.getElementById('signDiv');
var signDivUsername = document.getElementById('signDiv-username');
var signDivSignIn = document.getElementById('signDiv-signIn');
var signDivSignUp = document.getElementById('signDiv-signUp');
var signDivPassword = document.getElementById('signDiv-password');
signDivSignIn.onclick = function(){
socket.emit('signIn',{username:signDivUsername.value,password:signDivPassword.value});
}
signDivSignUp.onclick = function(){
socket.emit('signUp',{username:signDivUsername.value,password:signDivPassword.value});
}
socket.on('signInResponse',function(data){
if(data.success){
signDiv.style.display = 'none';
gameDiv.style.display = 'inline-block';
} else
alert("Sign in unsuccessul.");
});
socket.on('signUpResponse',function(data){
if(data.success){
alert("Sign up successul.");
} else
alert("Sign up unsuccessul.");
});
//chat
var chatText = document.getElementById('chat-text');
var chatInput = document.getElementById('chat-input');
var chatForm = document.getElementById('chat-form');
socket.on('addToChat',function(data){
chatText.innerHTML += '<div>' + data + '</div>';
});
socket.on('evalAnswer',function(data){
console.log(data);
});
chatForm.onsubmit = function(e){
e.preventDefault();
if(chatInput.value[0] === '/')
socket.emit('evalServer',chatInput.value.slice(1));
else
socket.emit('sendMsgToServer',chatInput.value);
chatInput.value = '';
}
//game
var Img = {};
Img.player = new Image();
Img.player.src = '/client/img/lamboS.png';
Img.bullet = new Image();
Img.bullet.src = '/client/img/bullet.png';
Img.map = new Image();
Img.map.src = '/client/img/road.png';
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
var Player = function(initPack){
var self = {};
self.id = initPack.id;
self.number = initPack.number;
self.x = initPack.x;
self.y = initPack.y;
self.hp = initPack.hp;
self.hpMax = initPack.hpMax;
self.score = initPack.score;
self.draw = function(){
// var x = self.x - Player.list[selfId].x + WIDTH/2;
// var y = self.y - Player.list[selfId].y + HEIGHT/2;
var hpWidth = 30 * self.hp / self.hpMax;
ctx.fillStyle = 'red';
ctx.fillRect(self.x - hpWidth/2,self.y - 40,hpWidth,4);
var width = Img.player.width;
var height = Img.player.height;
ctx.drawImage(Img.player,
0,0,Img.player.width,Img.player.height,
self.x-width/2,self.y-height/2,width,height);
//ctx.fillText(self.score,self.x,self.y-60);
}
Player.list[self.id] = self;
return self;
}
Player.list = {};
var Bullet = function(initPack){
var self = {};
self.id = initPack.id;
self.x = initPack.x;
self.y = initPack.y;
self.draw = function(){
var width = Img.bullet.width/2;
var height = Img.bullet.height/2;
// var x = self.x - Player.list[selfId].x + WIDTH/2;
// var y = self.y - Player.list[selfId].y + HEIGHT/2;
ctx.drawImage(Img.bullet,
0,0,Img.bullet.width,Img.bullet.height,
self.x-width/2,self.y-height/2,width,height);
}
Bullet.list[self.id] = self;
return self;
}
Bullet.list = {};
var selfId = null;
socket.on('init',function(data){
if(data.selfId)
selfId = data.selfId;
//{ player : [{id:123,number:'1',x:0,y:0},{id:1,number:'2',x:0,y:0}], bullet: []}
for(var i = 0 ; i < data.player.length; i++){
new Player(data.player[i]);
}
for(var i = 0 ; i < data.bullet.length; i++){
new Bullet(data.bullet[i]);
}
});
socket.on('update',function(data){
//{ player : [{id:123,x:0,y:0},{id:1,x:0,y:0}], bullet: []}
for(var i = 0 ; i < data.player.length; i++){
var pack = data.player[i];
var p = Player.list[pack.id];
if(p){
if(pack.x !== undefined)
p.x = pack.x;
if(pack.y !== undefined)
p.y = pack.y;
if(pack.hp !== undefined)
p.hp = pack.hp;
if(pack.score !== undefined)
p.score = pack.score;
}
}
for(var i = 0 ; i < data.bullet.length; i++){
var pack = data.bullet[i];
var b = Bullet.list[data.bullet[i].id];
if(b){
if(pack.x !== undefined)
b.x = pack.x;
if(pack.y !== undefined)
b.y = pack.y;
}
}
for(var i = 0 ; i < data.bullet.length; i++){
var pack = data.bullet[i];
var b = Bullet.list[data.bullet[i].id];
if(b){
if(pack.x !== undefined)
b.x = pack.x;
if(pack.y !== undefined)
b.y = pack.y;
}
}
});
socket.on('remove',function(data){
//{player:[12323],bullet:[12323,123123]}
for(var i = 0 ; i < data.player.length; i++){
delete Player.list[data.player[i]];
}
for(var i = 0 ; i < data.bullet.length; i++){
delete Bullet.list[data.bullet[i]];
}
});
setInterval(function(){
if(!selfId)
return;
ctx.clearRect(0,0,500,500);
drawMap();
drawScore();
for(var i in Player.list)
Player.list[i].draw();
for(var i in Bullet.list)
Bullet.list[i].draw();
},40);
var drawMap = function(){
var x = 0;
var y = 0;
// var x = WIDTH/2 - Player.list[selfId].x;
// var y = HEIGHT/2 - Player.list[selfId].y;
ctx.drawImage(Img.map, x, y);
// for(x = 0; x < 5; x += 100){
//// ctx.drawImage(Img.map, x, y);
// }
}
var drawScore = function(){
ctx.fillStyle = 'red';
ctx.fillText(Player.list[selfId].score,10,30);
}
document.onkeydown = function(event){
if(event.keyCode === 68) //d
socket.emit('keyPress',{inputId:'right',state:true});
else if(event.keyCode === 83) //s
socket.emit('keyPress',{inputId:'down',state:true});
else if(event.keyCode === 65) //a
socket.emit('keyPress',{inputId:'left',state:true});
else if(event.keyCode === 87) // w
socket.emit('keyPress',{inputId:'up',state:true});
}
document.onkeyup = function(event){
if(event.keyCode === 68) //d
socket.emit('keyPress',{inputId:'right',state:false});
else if(event.keyCode === 83) //s
socket.emit('keyPress',{inputId:'down',state:false});
else if(event.keyCode === 65) //a
socket.emit('keyPress',{inputId:'left',state:false});
else if(event.keyCode === 87) // w
socket.emit('keyPress',{inputId:'up',state:false});
}
document.onmousedown = function(event){
socket.emit('keyPress',{inputId:'attack',state:true});
}
document.onmouseup = function(event){
socket.emit('keyPress',{inputId:'attack',state:false});
}
document.onmousemove = function(event){
var x = -250 + event.clientX - 8;
var y = -250 + event.clientY - 8;
var angle = Math.atan2(y,x) / Math.PI * 180;
socket.emit('keyPress',{inputId:'mouseAngle',state:angle});
}
</script>
The idea in endless runners is to actually move the objects towards the player at constant speed(i.e. speed of the player). As soon as they get off the screen you can stop updating them. Check out this http://blog.sklambert.com/html5-game-tutorial-module-pattern/?utm_content=buffer18ac6&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer

Fabric.js: cannot get bounding box to match it's (dynamic) object

I am trying to give the user of a page the possibility to draw his/her own polygon onto an image. I use fabric.js (1.5.0) for that, and I borrowed quite some code from the examples there, however, in my case, the bounding boxes of the created polygons just don't match the polygons.
FireBug shows the points of the polygons being rather local than global, what is in my believe the cause of the problem. I'm kind of lost though in finding the crucial lines...
See the jsfiddle below for my example
https://jsfiddle.net/y9kqjLhk/
Any ideas?
Thanks
i hade the same issue a few months ago, as i wanted to draw a dynamic polygon with mouse click.
i give you an example on jsfiddle that you can do exactly what you need, the only difference is that i use the previous version of fabricjs .
i hope it helps, good luck.
this is the code and below i give the live jsfiddle example:
var roof = null;
var roofPoints = [];
var lines = [];
var lineCounter = 0;
var drawingObject = {};
drawingObject.type = "";
drawingObject.background = "";
drawingObject.border = "";
function Point(x, y) {
this.x = x;
this.y = y;
}
$("#btnRoof").click(function () {
if (drawingObject.type == "roof") {
drawingObject.type = "";
lines.forEach(function(value, index, ar){
canvas.remove(value);
});
//canvas.remove(lines[lineCounter - 1]);
roof = makeRoof(roofPoints);
canvas.add(roof);
canvas.renderAll();
} else {
drawingObject.type = "roof"; // roof type
}
});
// canvas Drawing
var canvas = new fabric.Canvas('canvas',{backgroundColor : 'yellow'});
var x = 0;
var y = 0;
fabric.util.addListener(window,'dblclick', function(){
drawingObject.type = "";
lines.forEach(function(value, index, ar){
canvas.remove(value);
});
//canvas.remove(lines[lineCounter - 1]);
roof = makeRoof(roofPoints);
canvas.add(roof);
canvas.renderAll();
console.log("double click");
//clear arrays
roofPoints = [];
lines = [];
lineCounter = 0;
});
canvas.on('mouse:down', function (options) {
if (drawingObject.type == "roof") {
canvas.selection = false;
setStartingPoint(options); // set x,y
roofPoints.push(new Point(x, y));
var points = [x, y, x, y];
lines.push(new fabric.Line(points, {
strokeWidth: 1,
selectable: false,
stroke: 'red'
}).setOriginX(x).setOriginY(y));
canvas.add(lines[lineCounter]);
lineCounter++;
canvas.on('mouse:up', function (options) {
canvas.selection = true;
});
}
});
canvas.on('mouse:move', function (options) {
if (lines[0] !== null && lines[0] !== undefined && drawingObject.type == "roof") {
setStartingPoint(options);
lines[lineCounter - 1].set({
x2: x,
y2: y
});
canvas.renderAll();
}
});
function setStartingPoint(options) {
var offset = $('#canvas').offset();
x = options.e.pageX - offset.left;
y = options.e.pageY - offset.top;
}
function makeRoof(roofPoints) {
var left = findLeftPaddingForRoof(roofPoints);
var top = findTopPaddingForRoof(roofPoints);
roofPoints.push(new Point(roofPoints[0].x,roofPoints[0].y))
var roof = new fabric.Polyline(roofPoints, {
fill: 'rgba(0,0,0,0)',
stroke:'#7F7F7F'
});
roof.set({
left: left,
top: top,
});
return roof;
}
function findTopPaddingForRoof(roofPoints) {
var result = 999999;
for (var f = 0; f < lineCounter; f++) {
if (roofPoints[f].y < result) {
result = roofPoints[f].y;
}
}
return Math.abs(result);
}
function findLeftPaddingForRoof(roofPoints) {
var result = 999999;
for (var i = 0; i < lineCounter; i++) {
if (roofPoints[i].x < result) {
result = roofPoints[i].x;
}
}
return Math.abs(result);
}
jsfiddle: http://jsfiddle.net/tornado1979/svb3q6xL/1/
click on the label to start drawind and stop drawing on mouse double click, enywhere on canvas.

javascript function didn't work in chrome

i have this function witch shows the user a loadingpanel at postback.
It works fine in IE and Firefox.
But Chrome showed me this Error:
I don't understand why. Does anyone have an idea?
I mean why it works in IE and Firefox. Where is the difference that it doesn't work in Chrome?
(function(){
var emptyFn = function(){};
function lp(d) {
this.converter = d.converter;
this.data = d.path || d.data;
this.imageData = [];
this.multiplier = d.multiplier || 1;
this.padding = d.padding || 0;
this.fps = d.fps || 25;
this.stepsPerFrame = ~~d.stepsPerFrame || 1;
this.trailLength = d.trailLength || 1;
this.pointDistance = d.pointDistance || .05;
this.domClass = d.domClass || 'lp';
this.backgroundColor = d.backgroundColor || 'rgba(0,0,0,0)';
this.fillColor = d.fillColor;
this.strokeColor = d.strokeColor;
this.stepMethod = typeof d.step == 'string' ?
stepMethods[d.step] :
d.step || stepMethods.square;
this._setup = d.setup || emptyFn;
this._teardown = d.teardown || emptyFn;
this._preStep = d.preStep || emptyFn;
this.width = d.width;
this.height = d.height;
this.fullWidth = this.width + 2*this.padding;
this.fullHeight = this.height + 2*this.padding;
this.domClass = d.domClass || 'lp';
this.setup();
}
var argTypes = lp.argTypes = {
DIM: 1,
DEGREE: 2,
RADIUS: 3,
OTHER: 0
};
var argSignatures = lp.argSignatures = {
arc: [1, 1, 3, 2, 2, 0],
bezier: [1, 1, 1, 1, 1, 1, 1, 1],
line: [1,1,1,1]
};
var pathMethods = lp.pathMethods = {
bezier: function(t, p0x, p0y, p1x, p1y, c0x, c0y, c1x, c1y) {
t = 1-t;
var i = 1-t,
x = t*t,
y = i*i,
a = x*t,
b = 3 * x * i,
c = 3 * t * y,
d = y * i;
return [
a * p0x + b * c0x + c * c1x + d * p1x,
a * p0y + b * c0y + c * c1y + d * p1y
]
},
arc: function(t, cx, cy, radius, start, end) {
var point = (end - start) * t + start;
var ret = [
(Math.cos(point) * radius) + cx,
(Math.sin(point) * radius) + cy
];
ret.angle = point;
ret.t = t;
return ret;
},
line: function(t, sx, sy, ex, ey) {
return [
(ex - sx) * t + sx,
(ey - sy) * t + sy
]
}
};
var stepMethods = lp.stepMethods = {
square: function(point, i, f, color, alpha) {
this._.fillRect(point.x - 3, point.y - 3, 6, 6);
},
fader: function(point, i, f, color, alpha) {
this._.beginPath();
if (this._last) {
this._.moveTo(this._last.x, this._last.y);
}
this._.lineTo(point.x, point.y);
this._.closePath();
this._.stroke();
this._last = point;
}
}
lp.prototype = {
setup: function() {
var args,
type,
method,
value,
data = this.data;
this.canvas = document.createElement('canvas');
this._ = this.canvas.getContext('2d');
this.canvas.className = this.domClass;
this.canvas.height = this.fullHeight;
this.canvas.width = this.fullWidth;
this.canvas.innerHTML = "<img src='../img/ContentLoad.gif' width='60px' height='60px' alt='Wird geladen' style='margin-top: 30px;' />"
this.points = [];
for (var i = -1, l = data.length; ++i < l;) {
args = data[i].slice(1);
method = data[i][0];
if (method in argSignatures) for (var a = -1, al = args.length; ++a < al;) {
type = argSignatures[method][a];
value = args[a];
switch (type) {
case argTypes.RADIUS:
value *= this.multiplier;
break;
case argTypes.DIM:
value *= this.multiplier;
value += this.padding;
break;
case argTypes.DEGREE:
value *= Math.PI/180;
break;
};
args[a] = value;
}
args.unshift(0);
for (var r, pd = this.pointDistance, t = pd; t <= 1; t += pd) {
t = Math.round(t*1/pd) / (1/pd);
args[0] = t;
r = pathMethods[method].apply(null, args);
this.points.push({
x: r[0],
y: r[1],
progress: t
});
}
}
this.frame = 0;
if (this.converter && this.converter.setup) {
this.converter.setup(this);
}
},
prep: function(frame) {
if (frame in this.imageData) {
return;
}
this._.clearRect(0, 0, this.fullWidth, this.fullHeight);
this._.fillStyle = this.backgroundColor;
this._.fillRect(0, 0, this.fullWidth, this.fullHeight);
var points = this.points,
pointsLength = points.length,
pd = this.pointDistance,
point,
index,
frameD;
this._setup();
for (var i = -1, l = pointsLength*this.trailLength; ++i < l && !this.stopped;) {
index = frame + i;
point = points[index] || points[index - pointsLength];
if (!point) continue;
this.alpha = Math.round(1000*(i/(l-1)))/1000;
this._.globalAlpha = this.alpha;
if (this.fillColor) {
this._.fillStyle = this.fillColor;
}
if (this.strokeColor) {
this._.strokeStyle = this.strokeColor;
}
frameD = frame/(this.points.length-1);
indexD = i/(l-1);
this._preStep(point, indexD, frameD);
this.stepMethod(point, indexD, frameD);
}
this._teardown();
this.imageData[frame] = (
this._.getImageData(0, 0, this.fullWidth, this.fullWidth)
);
return true;
},
draw: function() {
if (!this.prep(this.frame)) {
this._.clearRect(0, 0, this.fullWidth, this.fullWidth);
this._.putImageData(
this.imageData[this.frame],
0, 0
);
}
if (this.converter && this.converter.step) {
this.converter.step(this);
}
if (!this.iterateFrame()) {
if (this.converter && this.converter.teardown) {
this.converter.teardown(this);
this.converter = null;
}
}
},
iterateFrame: function() {
this.frame += this.stepsPerFrame;
if (this.frame >= this.points.length) {
this.frame = 0;
return false;
}
return true;
},
play: function() {
this.stopped = false;
var hoc = this;
this.timer = setInterval(function(){
hoc.draw();
}, 1000 / this.fps);
},
stop: function() {
this.stopped = true;
this.timer && clearInterval(this.timer);
}
};
window.lp = lp;
}());
function ContentLoader(e) {
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
if (isIE () == 8) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = '../img/ContentLoad.gif';
div.innerHTML = "<b style='color: #1d4377; z-index: 5000;'>Ihre Anfrage wird bearbeitet...</b><br /><i>...einen Moment bitte...</i><br />";
div.style.cssText = 'position: fixed; z-index: 6000; width: 100%; padding-top: 20%; left: 0; top: 0; height: 100%; text-align: center; background: #fff; filter: alpha(opacity=70);';
div.appendChild(img);
img.style.cssText = 'margin-top:20px;'
document.body.appendChild(div);
} else {
var div = document.createElement('div');
var circle = new lp({
width: 60,
height: 60,
padding: 50,
strokeColor: '#1d4377',
pointDistance: .01,
stepsPerFrame: 4,
trailLength: .8,
step: 'fader',
setup: function () {
this._.lineWidth = 5;
},
path: [
['arc', 25, 25, 25, 0, 360]
]
});
circle.play();
div.innerHTML = "<b style='color: #1d4377; z-index: 5000;'>Ihre Anfrage wird bearbeitet...</b><br /><i>...einen Moment bitte...</i><br />";
div.style.cssText = 'position: fixed; z-index: 6000; width: 100%; padding-top: 20%; left: 0; top: 0; height: 100%; text-align: center; background: #fff; opacity: 0.7;';
div.appendChild(circle.canvas);
document.body.appendChild(div);
}
}
Edit:
I call it like this:
<form id="frmTilgungsaussetzungErgebnis" runat="server" enctype="multipart/form-data" onsubmit="ContentLoader();">
Your function lp is not defined in the else scope.
Try
var circle = new this.lp({
instade
var circle = new lp({

Categories

Resources