I have a small problem and I can't get it to fix.
I developed a element that is following the cursor and way it needs to function is that the border around the cursor needs to stick with the position of the cursor. But the problem I've got right now is that it won't stick when scrolling down.
You can check at the demo below what I mean.
The problem seems that it is not correctly checking the height of the page, thats why its not correctly positioning. Am I right?
const windowW = window.innerWidth;
const windowH = window.innerHeight;
const maxLength = Math.max(windowW, windowH);
const cursorWidth = 100;
const cursorR = cursorWidth >> 1;
const cursorDelay = 10;
const buttons = Array.from(document.querySelectorAll('.border-button'));
const cursor = {
el: document.querySelector('.border-cursor'),
x: windowW >> 1,
y: windowH >> 1,
scaleX: 1,
scaleY: 1,
};
const target = {
x: windowW >> 1,
y: windowH >> 1,
width: cursorWidth,
followMouse: true,
};
const norm = (val, max, min) => (val - min) / (max - min);
const toDegrees = r => r * (180 / Math.PI);
const distanceBetween = (v1, v2) => Math.sqrt((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y +- v2.y));
const loop = () => {
const destX = target.x - cursorR;
const destY = target.y - cursorR;
const newX = cursor.x + ((destX - cursor.x) / cursorDelay);
const newY = cursor.y + ((destY - cursor.y) / cursorDelay);
const angle = angleBetween(cursor.x, cursor.y, newX, newY);
if (target.followMouse) {
const distance = Math.abs(distanceBetween(target, cursor));
const scale = norm(distance, maxLength, cursorR);
cursor.scaleX = 1 + scale;
cursor.scaleY = 1 - scale;
} else {
const targetScale = target.width / cursorWidth;
cursor.scaleX += (targetScale - cursor.scaleX) / (cursorDelay / 2);
cursor.scaleY = cursor.scaleX;
}
cursor.x = newX;
cursor.y = newY;
cursor.el.style.transform = `translate(${cursor.x}px, ${cursor.y}px) rotate(${toDegrees(angle)}deg) scale(${cursor.scaleX}, ${cursor.scaleY})`;
requestAnimationFrame(loop);
};
const angleBetween = (x1, y1, x2, y2) => Math.atan2(y2 - y1, x2 - x1);
const onPointerMove = (e) => {
if (!target.followMouse) {
return;
}
const pointer = (e.touches && e.touches.length) ? e.touches[0] : e;
const { clientX: x, clientY: y } = pointer;
target.x = x;
target.y = y;
};
const onPointerOver = (e) => {
const btn = e.target;
const rect = btn.getBoundingClientRect();
target.followMouse = false;
target.x = rect.left + (rect.width >> 1);
target.y = rect.top + (rect.height >> 1);
target.width = Math.max(rect.width, rect.height) + 50;
};
const onPointerOut = () => {
target.followMouse = true;
target.width = cursorWidth;
};
document.body.addEventListener('mousemove', onPointerMove);
document.body.addEventListener('touchmove', onPointerMove);
buttons.forEach((btn) => {
btn.addEventListener('touchstart', onPointerOver);
btn.addEventListener('mouseover', onPointerOver);
btn.addEventListener('touchend', onPointerOut);
btn.addEventListener('mouseout', onPointerOut);
});
loop();
const windowW = window.innerWidth;
const windowH = window.innerHeight;
const maxLength = Math.max(windowW, windowH);
const cursorWidth = 100;
const cursorR = cursorWidth >> 1;
const cursorDelay = 10;
const buttons = Array.from(document.querySelectorAll('.border-button'));
const cursor = {
el: document.querySelector('.border-cursor'),
x: windowW >> 1,
y: windowH >> 1,
scaleX: 1,
scaleY: 1,
};
const target = {
x: windowW >> 1,
y: windowH >> 1,
width: cursorWidth,
followMouse: true,
};
const norm = (val, max, min) => (val - min) / (max - min);
const toDegrees = r => r * (180 / Math.PI);
const distanceBetween = (v1, v2) => Math.sqrt((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y +- v2.y));
const loop = () => {
const destX = target.x - cursorR;
const destY = target.y - cursorR;
const newX = cursor.x + ((destX - cursor.x) / cursorDelay);
const newY = cursor.y + ((destY - cursor.y) / cursorDelay);
const angle = angleBetween(cursor.x, cursor.y, newX, newY);
if (target.followMouse) {
const distance = Math.abs(distanceBetween(target, cursor));
const scale = norm(distance, maxLength, cursorR);
cursor.scaleX = 1 + scale;
cursor.scaleY = 1 - scale;
} else {
const targetScale = target.width / cursorWidth;
cursor.scaleX += (targetScale - cursor.scaleX) / (cursorDelay / 2);
cursor.scaleY = cursor.scaleX;
}
cursor.x = newX;
cursor.y = newY;
cursor.el.style.transform = `translate(${cursor.x}px, ${cursor.y}px) rotate(${toDegrees(angle)}deg) scale(${cursor.scaleX}, ${cursor.scaleY})`;
requestAnimationFrame(loop);
};
const angleBetween = (x1, y1, x2, y2) => Math.atan2(y2 - y1, x2 - x1);
const onPointerMove = (e) => {
if (!target.followMouse) {
return;
}
const pointer = (e.touches && e.touches.length) ? e.touches[0] : e;
const { clientX: x, clientY: y } = pointer;
target.x = x;
target.y = y;
};
const onPointerOver = (e) => {
const btn = e.target;
const rect = btn.getBoundingClientRect();
target.followMouse = false;
target.x = rect.left + (rect.width >> 1);
target.y = rect.top + (rect.height >> 1);
target.width = Math.max(rect.width, rect.height) + 50;
};
const onPointerOut = () => {
target.followMouse = true;
target.width = cursorWidth;
};
document.body.addEventListener('mousemove', onPointerMove);
document.body.addEventListener('touchmove', onPointerMove);
buttons.forEach((btn) => {
btn.addEventListener('touchstart', onPointerOver);
btn.addEventListener('mouseover', onPointerOver);
btn.addEventListener('touchend', onPointerOut);
btn.addEventListener('mouseout', onPointerOut);
});
loop();
html,
body {
margin: 0;
padding: 0;
}
.wrapper {
width: 100vw;
min-height: 1500px;
display: flex;
flex-direction: row;
align-items: center;
}
.container {
width: 100%;
display: flex;
padding: 0 1rem;
}
.cursor {
position: absolute;
z-index: 10;
width: 100px;
height: 100px;
border: 2px solid #23bfa0;
border-radius: 50%;
pointer-events: none;
}
.button {
padding: 1rem;
background-color: #23bfa0;
border: none;
box-shadow: 0 0 7px 0px rgba(0, 0, 0, 0.2);
color: white;
font-size: 1.2rem;
cursor: pointer;
transition: box-shadow 0.1s ease-in, transform 0.1s ease-in;
&--small {
padding: 0.75rem;
font-size: 0.75rem;
}
&:hover {
transform: translate(0%, -2px);
box-shadow: 0px 4px 9px 2px rgba(0, 0, 0, 0.2)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="cursor border-cursor"></div>
<div class="wrapper">
<div class="container">
<button class="button button--small border-button">small</button>
<button class="button border-button">hover me</button>
<button class="button border-button">hover me more</button>
</div>
</div>
</body>
In onPointerMove, try replacing:
const { clientX: x, clientY: y } = pointer;
with:
const { pageX: x, pageY: y } = pointer;
Here's a good post explaining the differences between these values:
https://stackoverflow.com/a/9335517/965834
Also, change:
target.x = rect.left + (rect.width >> 1);
target.y = rect.top + (rect.height >> 1);
into:
target.x = window.scrollX + rect.left + (rect.width >> 1);
target.y = window.scrollY + rect.top + (rect.height >> 1);
This takes into account scrolling when calculating the position of your buttons.
Demo:
const windowW = window.innerWidth;
const windowH = window.innerHeight;
const maxLength = Math.max(windowW, windowH);
const cursorWidth = 100;
const cursorR = cursorWidth >> 1;
const cursorDelay = 10;
const buttons = Array.from(document.querySelectorAll('.border-button'));
const cursor = {
el: document.querySelector('.border-cursor'),
x: windowW >> 1,
y: windowH >> 1,
scaleX: 1,
scaleY: 1,
};
const target = {
x: windowW >> 1,
y: windowH >> 1,
width: cursorWidth,
followMouse: true,
};
const norm = (val, max, min) => (val - min) / (max - min);
const toDegrees = r => r * (180 / Math.PI);
const distanceBetween = (v1, v2) => Math.sqrt((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y +- v2.y));
const loop = () => {
const destX = target.x - cursorR;
const destY = target.y - cursorR;
const newX = cursor.x + ((destX - cursor.x) / cursorDelay);
const newY = cursor.y + ((destY - cursor.y) / cursorDelay);
const angle = angleBetween(cursor.x, cursor.y, newX, newY);
if (target.followMouse) {
const distance = Math.abs(distanceBetween(target, cursor));
const scale = norm(distance, maxLength, cursorR);
cursor.scaleX = 1 + scale;
cursor.scaleY = 1 - scale;
} else {
const targetScale = target.width / cursorWidth;
cursor.scaleX += (targetScale - cursor.scaleX) / (cursorDelay / 2);
cursor.scaleY = cursor.scaleX;
}
cursor.x = newX;
cursor.y = newY;
cursor.el.style.transform = `translate(${cursor.x}px, ${cursor.y}px) rotate(${toDegrees(angle)}deg) scale(${cursor.scaleX}, ${cursor.scaleY})`;
requestAnimationFrame(loop);
};
const angleBetween = (x1, y1, x2, y2) => Math.atan2(y2 - y1, x2 - x1);
const onPointerMove = (e) => {
if (!target.followMouse) {
return;
}
const pointer = (e.touches && e.touches.length) ? e.touches[0] : e;
const { pageX: x, pageY: y } = pointer;
target.x = x;
target.y = y;
};
const onPointerOver = (e) => {
const btn = e.target;
const rect = btn.getBoundingClientRect();
target.followMouse = false;
target.x = window.scrollX + rect.left + (rect.width >> 1);
target.y = window.scrollY + rect.top + (rect.height >> 1);
target.width = Math.max(rect.width, rect.height) + 50;
};
const onPointerOut = () => {
target.followMouse = true;
target.width = cursorWidth;
};
document.body.addEventListener('mousemove', onPointerMove);
document.body.addEventListener('touchmove', onPointerMove);
buttons.forEach((btn) => {
btn.addEventListener('touchstart', onPointerOver);
btn.addEventListener('mouseover', onPointerOver);
btn.addEventListener('touchend', onPointerOut);
btn.addEventListener('mouseout', onPointerOut);
});
loop();
html,
body {
margin: 0;
padding: 0;
}
.wrapper {
width: 100vw;
min-height: 1500px;
display: flex;
flex-direction: row;
align-items: center;
}
.container {
width: 100%;
display: flex;
padding: 0 1rem;
}
.cursor {
position: absolute;
z-index: 10;
width: 100px;
height: 100px;
border: 2px solid #23bfa0;
border-radius: 50%;
pointer-events: none;
}
.button {
padding: 1rem;
background-color: #23bfa0;
border: none;
box-shadow: 0 0 7px 0px rgba(0, 0, 0, 0.2);
color: white;
font-size: 1.2rem;
cursor: pointer;
transition: box-shadow 0.1s ease-in, transform 0.1s ease-in;
&--small {
padding: 0.75rem;
font-size: 0.75rem;
}
&:hover {
transform: translate(0%, -2px);
box-shadow: 0px 4px 9px 2px rgba(0, 0, 0, 0.2)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="cursor border-cursor"></div>
<div class="wrapper">
<div class="container">
<button class="button button--small border-button">small</button>
<button class="button border-button">hover me</button>
<button class="button border-button">hover me more</button>
</div>
</div>
</body>
Related
I am trying to draw a path between points wihtout using canvas or any other librares.
Everything works fine for positive degrees, but it doesn't for negative..
My "points" are 150x150 [px], that's why there is that +75px in left position.
This is my code:
useEffect(() => {
let x1 = spider1.x;
let y1 = spider1.y;
let x2 = spider2.x;
let y2 = spider2.y;
if (x1 > x2) {
let xTmp = x1;
let yTmp = y1;
x1 = x2;
y1 = y2;
x2 = xTmp;
y2 = yTmp;
}
if (x1 === x2) {
const height = Math.abs(y2 - y1).toString();
setStyle({
width: '5px',
left: (x1 + 75).toString() + 'px',
top: `${Math.min(y1, y2) + 75}px`,
height: `${height}px`,
transform: 'rotate(0deg)'
});
} else {
const a = (y2 - y1) / (x2 - x1);
const radians = Math.atan(a);
const degrees = radians * (180 / Math.PI);
setStyle({
width: `${Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))}px`,
left: (x1 + 75).toString() + 'px',
top: `${Math.min(y1, y2) + 75}px`,
height: `5px`,
transform: `rotate(${degrees}deg)`,
transformOrigin: `${degrees > 0 ? '0% 0%' : '100% 100%'}`
});
}
}, [spider1, spider2]);
return <div className='net' style={style} ref={myRef}></div>;
And the net class:
.net {
position: absolute;
background-color: red;
z-index: 90;
}
On the screens we have the same objects, but the degrees on the second one are "-" and the line doesn't connect that two squares because of that
This example works. You will have to compare yours with mine as to what the differences are.
Note: I just wrote it from scratch rather using your example.
Just click "Random position"
var button = document.getElementById("new-points");
button.onclick = function() {
var xy1 = {
m_x : Math.floor((Math.random() * 200) + 1),
m_y : Math.floor((Math.random() * 200) + 1),
};
var xy2 = {
m_x : Math.floor((Math.random() * 200) + 1),
m_y : Math.floor((Math.random() * 200) + 1),
};
var dotA = document.getElementById("dotA");
dotA.style.left = (xy1.m_x - 5) + "px";
dotA.style.top = (xy1.m_y - 5) + "px";
var dotB = document.getElementById("dotB");
dotB.style.left = (xy2.m_x - 5) + "px";
dotB.style.top = (xy2.m_y - 5) + "px";
var line = document.getElementById("line");
var distance = Math.hypot(xy2.m_x - xy1.m_x, xy2.m_y - xy1.m_y);
line.style.width = distance + "px";
line.style.left = xy1.m_x + "px";
line.style.top = xy1.m_y + "px";
var angle = ((Math.atan2(xy1.m_x - xy2.m_x, xy2.m_y - xy1.m_y) + (Math.PI / 2.0)) * 180 / Math.PI);
line.style.transform = "rotate(" + angle + "deg)";
line.style.display = "block";
}
#new-points {
border: 1px solid black;
padding: 5px;
width: 200px;
text-align: center;
}
.dot {
position: absolute;
width: 10px;
height: 10px;
background: blue;
}
#line {
position: absolute;
border-top: solid 1px red;
height: 1px;
max-height: 1px;
transform-origin: 0% 0%;
}
<div id="dotA" class="dot"></div>
<div id="dotB" class="dot"></div>
<div id="line"></div>
<div id="new-points" style="">
Random position
</div>
I've also tried the atan method for the above and it doesn't work. You can try it yourself and see what happens.
i am trying to get alert from the main big circle alone. The alert should not come from the small circles.
How to get alert from the big circle alone? and Text for small circle should be in the bottom the each circle. For me its showing in the top right corner of the circles. Can anyone help me to solve this thing?
Thanks in advance
var noop = function() {
return this;
};
function UserCanceledError() {
this.name = 'UserCanceledError';
this.message = 'User canceled dialog';
}
UserCanceledError.prototype = Object.create(Error.prototype);
function Dialog() {
this.setCallbacks(noop, noop);
}
Dialog.prototype.setCallbacks = function(okCallback, cancelCallback) {
this._okCallback = okCallback;
return this;
};
Dialog.prototype.waitForUser = function() {
var _this = this;
return new Promise(function(resolve, reject) {
_this.setCallbacks(resolve, reject);
});
};
Dialog.prototype.show = noop;
Dialog.prototype.hide = noop;
function PromptDialog() {
Dialog.call(this);
this.el = document.getElementById('dialog');
this.messageEl = this.el.querySelector('.message');
this.okButton = this.el.querySelector('button.ok');
this.attachDomEvents();
}
PromptDialog.prototype = Object.create(Dialog.prototype);
PromptDialog.prototype.attachDomEvents = function() {
var _this = this;
this.okButton.addEventListener('click', function() {
_this.hide();
console.log('Ok clicked!!');
});
};
PromptDialog.prototype.show = function(message) {
this.messageEl.innerHTML = '' + message;
this.el.className = '';
return this;
};
PromptDialog.prototype.hide = function() {
this.el.className = 'hidden';
return this;
};
var prompt = new PromptDialog();
const getBall = (x, y, dx, dy, r, color) => ({x, y, dx, dy, r, color});
const drawBall = (ball, ctx) => {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
ctx.fillStyle = ball.collider ? "red" : ball.color;
ctx.fill();
ctx.closePath();
}
const updatePos = (ball, containerR) => {
ball.x += ball.dx;
ball.y += ball.dy;
const dx = ball.x - containerR;
const dy = ball.y - containerR;
if (Math.sqrt(dx * dx + dy * dy) >= containerR - ball.r) {
const v = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
const angleToCollisionPoint = Math.atan2(-dy, dx);
const oldAngle = Math.atan2(-ball.dy, ball.dx);
const newAngle = 2 * angleToCollisionPoint - oldAngle;
ball.dx = -v * Math.cos(newAngle);
ball.dy = v * Math.sin(newAngle);
}
}
function makeArea(domid, radius, ballsNumber) {
const ctx = document.getElementById(domid).getContext("2d");
const containerR = radius;
const size = radius * 2
ctx.canvas.width = ctx.canvas.height = size;
ctx.globalAlpha = 1;
let balls = [];
for(var i=0 ; i<ballsNumber ; ++i) {
const r = Math.random()*radius*0.5;
const t = Math.random()*Math.PI*2;
balls.push(getBall(radius + Math.cos(t)*r, radius + Math.sin(t)*r, 0.1, 0.1, 5, "Green"));
}
return {
ctx: ctx,
radius: radius,
balls: balls
}
}
const collides = (a, b) => (Math.hypot(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) < (a.r + b.r));
const areas = [
makeArea("Canvas", 150, 10, true),
makeArea("Canvas1", 80, 4, false),
makeArea("Canvas2", 80, 4, false),
makeArea("Canvas3", 80, 4, false),
makeArea("Canvas4", 80, 4, false)
];
function engine() {
//console.clear(); // Clear console test messages
mydiv.textContent =" ";
areas.forEach((area) =>{
const ctx = area.ctx;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
area.balls.forEach((a, ai) => {
a.collider = undefined;
area.balls.forEach((b, bi) => {
if (bi === ai) return; // Don't look at self
if (collides(a, b)) a.collider = b; // Store the colliding B ball
});
if (a.collider) { // If ball has a collider:
//mydiv.textContent = ("Alert");
//beep();
prompt.show('ALERT!!!!! Not Maintaining Distance')
.waitForUser()
.then(function(name) {
output.innerHTML = '' + name;
})
.catch(function(e) {
console.log('Unknown error', e);
})
.finally(function() {
prompt.hide();
});
//console.log(`${a.color[0]} → ← ${a.collider.color[0]}`);
}
updatePos(a, area.radius);
drawBall(a, ctx);
});
});
requestAnimationFrame(engine);
}
engine();
canvas {
background: #eee;
margin: 0 auto;
border-radius: 50%;
box-shadow: 0 0 0 4px #000;
}
.row {
display: flex;
}
.Row {
display: flex;
flex-direction: row;
margin-left: 40%;
margin-top: 8%;
float: right;
}
#Canvas1, #Canvas2, #Canvas3, #Canvas4 {
background: #eee;
border-radius: 50%;
border: solid 0px #000;
margin: 2px;
}
<div class="Row">
<div>
<canvas id="Canvas"></canvas>
</div>
<div>
<div class="row">
<canvas id="Canvas1"></canvas>
<span> xyz</span>
<canvas id="Canvas2"></canvas>
<span> xyz1</span>
</div>
<div class="row">
<canvas id="Canvas3"></canvas>
<span> xyz2</span>
<canvas id="Canvas4"></canvas>
<span>xyz3</span>
</div>
</div>
</div>
<div id="mydiv"></div>
<div id="dialog" class="hidden">
<div class="message"></div>
<div>
<button class="ok">OK</button>
</div>
</div>
Regarding your second question:
The <span>s are just children of .row, like the canvas is. You could "group" them with the canvas and make their position absolute:
/* important stuff: */
.group {
position: relative;
}
.group span {
position: absolute;
left: 0;
right: 0;
bottom: 5px;
text-align: center;
}
/* only for testing: */
#canvas1 {
background: #eee;
width: 100%;
height: 100%
}
.row {
width: 200px;
height: 200px;
display: flex;
}
<div class="row">
<div class="group">
<canvas id="canvas1"></canvas>
<span>xyz</span>
</div>
</div>
About the alert from the big circle:
If you're extending your forEach on all areas with a variable for the index ...
areas.forEach((area, areaindex) => {
... you could check for index zero later:
if (a.collider && areaindex == 0)
i have a html script with button and onclick function script that should take me to google.com, but it doesn't seem to work. Been stuck with this for hours. Im also new to HTML.
Tried everything. Line 336 and 353 should be the needed content. And line 136 should be the button itself. I don't understand whats wrong. Anyone ever have had this issue?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon/text/javascript" href="https://static.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico" />
<link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg" color="#111" />
<title>SpyBanter - SpyBanter's Official WebSite</title>
<style type="text/css">
body {
overflow: hidden;
margin: 0;
}
body:before {
content: '';
background: #c4252a url(http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/cheap_diagonal_fabric.png);
background-blend-mode: multiply;
mix-blend-mode: multiply;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 10;
}
canvas {
opacity: 0;
transition: 1s opacity cubic-bezier(0.55, 0, 0.1, 1);
}
canvas.ready {
opacity: 0.4;
}
.intro {
position: absolute;
padding: 20px;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
text-align: center;
color: #fafafa;
z-index: 10;
width: 100%;
max-width: 700px;
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
text-shadow: 0px 5px 20px black;
}
.intro h1 {
font-size: 40px;
font-weight: 300;
letter-spacing: 2px;
}
.intro p {
letter-spacing: 1px;
line-height: 24px;
}
#btnclose {
background-color: indianred;
border-color: darkred;
}
}
#btnnup:hover, #btnsisu:hover, #btncmd:hover {
background-color: #3e8e41;
}
#btnnup:active, #btnsisu:active, #btncmd:active {
background-color: #3e8e41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
#btnsisu {
left: 108px;
top: 105px;
}
#btncmd {
left: -311px;
top: -88px;
}
#content {
width: 100%;
height: auto;
min-height: 580px;
}
</style>
<script>
window.console = window.console || function(t) {};
</script>
<script>
if (document.location.search.match(/type=embed/gi)) {
window.parent.postMessage("resize", "*");
}
</script>
</head>
<body translate="no">
<canvas id="canvas" data-image="http://unsplash.it/g/450/200/?random=1"></canvas>
<div class="intro">
<h1>Interactive mosaic background</h1>
<p>Had to do this effect in a recent project and wanted to share it with you :). To change the background, edit the data-image on the canvas tag. You can also change the magnet effect intensity by changing the magnet variable</p>
<button id="btncmd">Videos</button>
</div>
<script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-de7e2ef6bfefd24b79a3f68b414b87b8db5b08439cac3f1012092b2290c719cd.js"></script>
<script type="application/javascript">
(function () {
// Variables
var Photo, addListeners, canvas, createGrid, ctx, gridItem, grids, height, img, imgInfo, imgSrc, imgs, init, magnet, mouse, populateCanvas, render, resizeCanvas, rotateAndPaintImage, updateMouse, useGrid, width;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
imgSrc = canvas.dataset.image;
img = new Image();
useGrid = true;
imgInfo = {};
imgs = [];
grids = [];
magnet = 2000;
mouse = {
x: 1,
y: 0 };
init = function () {
addListeners();
img.onload = function (e) {
var numberToShow;
// Check for firefox.
imgInfo.width = e.path ? e.path[0].width : e.target.width;
imgInfo.height = e.path ? e.path[0].height : e.target.height;
numberToShow = Math.ceil(window.innerWidth / imgInfo.width) * Math.ceil(window.innerHeight / imgInfo.height);
if (useGrid) {
createGrid();
}
populateCanvas(numberToShow * 4);
canvas.classList.add('ready');
return render();
};
return img.src = imgSrc;
};
addListeners = function () {
window.addEventListener('resize', resizeCanvas);
window.addEventListener('mousemove', updateMouse);
return window.addEventListener('touchmove', updateMouse);
};
updateMouse = function (e) {
mouse.x = e.clientX;
return mouse.y = e.clientY;
};
resizeCanvas = function () {
width = canvas.width = window.innerWidth;
return height = canvas.height = window.innerHeight;
};
populateCanvas = function (nb) {
var i, p, results;
i = 0;
results = [];
while (i <= nb) {
p = new Photo();
imgs.push(p);
results.push(i++);
}
return results;
};
createGrid = function () {
var c, grid, i, imgScale, item, j, k, l, r, ref, ref1, ref2, results, x, y;
imgScale = 0.5;
grid = {
row: Math.ceil(window.innerWidth / (imgInfo.width * imgScale)),
cols: Math.ceil(window.innerHeight / (imgInfo.height * imgScale)),
rowWidth: imgInfo.width * imgScale,
colHeight: imgInfo.height * imgScale };
for (r = j = 0, ref = grid.row; 0 <= ref ? j < ref : j > ref; r = 0 <= ref ? ++j : --j) {
x = r * grid.rowWidth;
for (c = k = 0, ref1 = grid.cols; 0 <= ref1 ? k < ref1 : k > ref1; c = 0 <= ref1 ? ++k : --k) {
y = c * grid.colHeight;
item = new gridItem(x, y, grid.rowWidth, grid.colHeight);
grids.push(item);
}
}
results = [];
for (i = l = 0, ref2 = grids.length; 0 <= ref2 ? l < ref2 : l > ref2; i = 0 <= ref2 ? ++l : --l) {
results.push(grids[i].draw());
}
return results;
};
gridItem = function (x = 0, y = 0, w, h) {
this.draw = function () {
ctx.drawImage(img, x, y, w, h);
};
};
Photo = function () {
var TO_RADIANS, finalX, finalY, forceX, forceY, h, r, seed, w, x, y;
seed = Math.random() * (2.5 - 0.7) + 0.7;
w = imgInfo.width / seed;
h = imgInfo.height / seed;
x = window.innerWidth * Math.random();
finalX = x;
y = window.innerHeight * Math.random();
finalY = y;
console.log(`INIT Y :: ${finalY} || INIT X :: ${finalX}`);
r = Math.random() * (180 - -180) + -180;
forceX = 0;
forceY = 0;
TO_RADIANS = Math.PI / 180;
this.update = function () {
var distance, dx, dy, powerX, powerY, x0, x1, y0, y1;
x0 = x;
y0 = y;
x1 = mouse.x;
y1 = mouse.y;
dx = x1 - x0;
dy = y1 - y0;
distance = Math.sqrt(dx * dx + dy * dy);
powerX = x0 - dx / distance * magnet / distance;
powerY = y0 - dy / distance * magnet / distance;
forceX = (forceX + (finalX - x0) / 2) / 2.1;
forceY = (forceY + (finalY - y0) / 2) / 2.2;
x = powerX + forceX;
y = powerY + forceY;
};
this.draw = function () {
return rotateAndPaintImage(ctx, img, r * TO_RADIANS, x, y, w / 2, h / 2, w, h);
};
};
rotateAndPaintImage = function (context, image, angle, positionX, positionY, axisX, axisY, widthX, widthY) {
context.translate(positionX, positionY);
context.rotate(angle);
context.drawImage(image, -axisX, -axisY, widthX, widthY);
context.rotate(-angle);
return context.translate(-positionX, -positionY);
};
render = function () {
var x, y;
x = 0;
y = 0;
ctx.clearRect(0, 0, width, height);
while (y < grids.length) {
grids[y].draw();
y++;
}
while (x < imgs.length) {
imgs[x].update();
imgs[x].draw();
x++;
}
return requestAnimationFrame(render);
};
init();
}).call(this);
cmd = function () {
window.location.href = "https://www.google.com/";
}
function cmd() {
window.location.href = "https://www.google.com/";
}
btnclose.onclick = cmd;
btnnup.onclick = cmd;
btncmd.onclick = cmd;
//# sourceURL=coffeescript
//# sourceURL=pen.js
</script>
<script type="application/javascript">
window.onload = function() {
main.style.opacity = "1";
}
function show(){
main.style.opacity = "1";
}
function close() {
main.style.opacity = "0";
$.post('http://tt_help/close', JSON.stringify({
}));
}
function cmd() {
window.location.href = "https://www.google.com/";
}
function sisukord() {
let id = $(this).attr('content');
console.log(id)
let docs = `https://docs.google.com/document/d/e/2PACX-1vSXxzowHucTNRBwduXT-pDoGQT4blGJhOvgnzIYmpEe2DwU4mimf84RZ8orvUGpm2vPsPDdkkVAnFkq/pub?embedded=true${id}`;
$('#main iframe').attr('src', docs);
}
window.addEventListener('message', function(event) {
if (event.data.type == "open") {
main.style.opacity = "1";
}
});
btnclose.onclick = cmd;
btncmd.onclick = cmd;
btnsisu.onclick = cmd;
</script>
</body>
If you're trying to make a button that takes you to google.com, I would advise you to use an a tag, not a button tag. The tag automatically links you to your desired destination when clicked.
Example:
Example
If you want the link to look like a button, then simply look at the css options. I would advise you to look here: https://www.w3schools.com/css/css_link.asp
a {
background-image:linear-gradient(to bottom, lightblue, aquamarine);
padding:5px;
text-decoration:none;
color:black;
padding-right:50px;
padding-left:50px;
margin-top: 50px;
margin-left: 50px;
display: inline-block;
font-size:25px;
border-radius:5px;
box-shadow: 1px 1px green;
}
Example
If you are determined to use a <button> tag, then all you need to do is within that button tag add an onclick attribute. So, you would change your code to <button id="btncmd" onclick="cmd()">Videos</button>.
Example of what you want:
function cmd() {
window.location.href = "https://www.example.com/"; // I'm using example but you can use google.
}
<button id="btncmd" onclick="cmd()">Videos</button>
You did not define btncmd. Adding this line to your code solves the problem:
var btncmd = document.getElementById("btncmd");
I make an object which has drag and resize. But I want this object dimension and position changes saved on the same where I left. Whenever I open the or reload the page I want the object position and resizing saved wherever I left last time.
How can I do this?
HTML Code is
<div id="pane">
<div id="title">Resize, Drag or Snap Me!</div>
</div>
<div id="ghostpane"></div>
CSS Code is
body {
overflow: hidden;
}
#pane {
position: absolute;
width: 45%;
height: 45%;
top: 20%;
left: 20%;
margin: 0;
padding: 0;
z-index: 99;
border: 2px solid purple;
background: #fefefe;
}
#title {
font-family: monospace;
background: purple;
color: white;
font-size: 24px;
height: 30px;
text-align: center;
}
#ghostpane {
background: #999;
opacity: 0.2;
width: 45%;
height: 45%;
top: 20%;
left: 20%;
position: absolute;
margin: 0;
padding: 0;
z-index: 98;
-webkit-transition: all 0.25s ease-in-out;
-moz-transition: all 0.25s ease-in-out;
-ms-transition: all 0.25s ease-in-out;
-o-transition: all 0.25s ease-in-out;
transition: all 0.25s ease-in-out;
}
JS Code is
"use strict";
// Minimum resizable area
var minWidth = 60;
var minHeight = 40;
// Thresholds
var FULLSCREEN_MARGINS = -10;
var MARGINS = 4;
// End of what's configurable.
var clicked = null;
var onRightEdge, onBottomEdge, onLeftEdge, onTopEdge;
var rightScreenEdge, bottomScreenEdge;
var preSnapped;
var b, x, y;
var redraw = false;
var pane = document.getElementById('pane');
var ghostpane = document.getElementById('ghostpane');
function setBounds(element, x, y, w, h) {
element.style.left = x + 'px';
element.style.top = y + 'px';
element.style.width = w + 'px';
element.style.height = h + 'px';
}
function hintHide() {
setBounds(ghostpane, b.left, b.top, b.width, b.height);
ghostpane.style.opacity = 0;
// var b = ghostpane.getBoundingClientRect();
// ghostpane.style.top = b.top + b.height / 2;
// ghostpane.style.left = b.left + b.width / 2;
// ghostpane.style.width = 0;
// ghostpane.style.height = 0;
}
// Mouse events
pane.addEventListener('mousedown', onMouseDown);
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
// Touch events
pane.addEventListener('touchstart', onTouchDown);
document.addEventListener('touchmove', onTouchMove);
document.addEventListener('touchend', onTouchEnd);
function onTouchDown(e) {
onDown(e.touches[0]);
e.preventDefault();
}
function onTouchMove(e) {
onMove(e.touches[0]);
}
function onTouchEnd(e) {
if (e.touches.length ==0) onUp(e.changedTouches[0]);
}
function onMouseDown(e) {
onDown(e);
e.preventDefault();
}
function onDown(e) {
calc(e);
var isResizing = onRightEdge || onBottomEdge || onTopEdge || onLeftEdge;
clicked = {
x: x,
y: y,
cx: e.clientX,
cy: e.clientY,
w: b.width,
h: b.height,
isResizing: isResizing,
isMoving: !isResizing && canMove(),
onTopEdge: onTopEdge,
onLeftEdge: onLeftEdge,
onRightEdge: onRightEdge,
onBottomEdge: onBottomEdge
};
}
function canMove() {
return x > 0 && x < b.width && y > 0 && y < b.height
&& y < 30;
}
function calc(e) {
b = pane.getBoundingClientRect();
x = e.clientX - b.left;
y = e.clientY - b.top;
onTopEdge = y < MARGINS;
onLeftEdge = x < MARGINS;
onRightEdge = x >= b.width - MARGINS;
onBottomEdge = y >= b.height - MARGINS;
rightScreenEdge = window.innerWidth - MARGINS;
bottomScreenEdge = window.innerHeight - MARGINS;
}
var e;
function onMove(ee) {
calc(ee);
e = ee;
redraw = true;
}
function animate() {
requestAnimationFrame(animate);
if (!redraw) return;
redraw = false;
if (clicked && clicked.isResizing) {
if (clicked.onRightEdge) pane.style.width = Math.max(x, minWidth) + 'px';
if (clicked.onBottomEdge) pane.style.height = Math.max(y, minHeight) + 'px';
if (clicked.onLeftEdge) {
var currentWidth = Math.max(clicked.cx - e.clientX + clicked.w, minWidth);
if (currentWidth > minWidth) {
pane.style.width = currentWidth + 'px';
pane.style.left = e.clientX + 'px';
}
}
if (clicked.onTopEdge) {
var currentHeight = Math.max(clicked.cy - e.clientY + clicked.h, minHeight);
if (currentHeight > minHeight) {
pane.style.height = currentHeight + 'px';
pane.style.top = e.clientY + 'px';
}
}
hintHide();
return;
}
if (clicked && clicked.isMoving) {
if (b.top < FULLSCREEN_MARGINS || b.left < FULLSCREEN_MARGINS || b.right > window.innerWidth - FULLSCREEN_MARGINS || b.bottom > window.innerHeight - FULLSCREEN_MARGINS) {
// hintFull();
setBounds(ghostpane, 0, 0, window.innerWidth, window.innerHeight);
ghostpane.style.opacity = 0.2;
} else if (b.top < MARGINS) {
// hintTop();
setBounds(ghostpane, 0, 0, window.innerWidth, window.innerHeight / 2);
ghostpane.style.opacity = 0.2;
} else if (b.left < MARGINS) {
// hintLeft();
setBounds(ghostpane, 0, 0, window.innerWidth / 2, window.innerHeight);
ghostpane.style.opacity = 0.2;
} else if (b.right > rightScreenEdge) {
// hintRight();
setBounds(ghostpane, window.innerWidth / 2, 0, window.innerWidth / 2, window.innerHeight);
ghostpane.style.opacity = 0.2;
} else if (b.bottom > bottomScreenEdge) {
// hintBottom();
setBounds(ghostpane, 0, window.innerHeight / 2, window.innerWidth, window.innerWidth / 2);
ghostpane.style.opacity = 0.2;
} else {
hintHide();
}
if (preSnapped) {
setBounds(pane,
e.clientX - preSnapped.width / 2,
e.clientY - Math.min(clicked.y, preSnapped.height),
preSnapped.width,
preSnapped.height
);
return;
}
// moving
pane.style.top = (e.clientY - clicked.y) + 'px';
pane.style.left = (e.clientX - clicked.x) + 'px';
return;
}
// This code executes when the mouse moves without clicking
// style cursor
if (onRightEdge && onBottomEdge || onLeftEdge && onTopEdge) {
pane.style.cursor = 'nwse-resize';
} else if (onRightEdge && onTopEdge || onBottomEdge && onLeftEdge) {
pane.style.cursor = 'nesw-resize';
} else if (onRightEdge || onLeftEdge) {
pane.style.cursor = 'ew-resize';
} else if (onBottomEdge || onTopEdge) {
pane.style.cursor = 'ns-resize';
} else if (canMove()) {
pane.style.cursor = 'move';
} else {
pane.style.cursor = 'default';
}
}
animate();
function onUp(e) {
calc(e);
if (clicked && clicked.isMoving) {
// Snap
var snapped = {
width: b.width,
height: b.height
};
if (b.top < FULLSCREEN_MARGINS || b.left < FULLSCREEN_MARGINS || b.right > window.innerWidth - FULLSCREEN_MARGINS || b.bottom > window.innerHeight - FULLSCREEN_MARGINS) {
// hintFull();
setBounds(pane, 0, 0, window.innerWidth, window.innerHeight);
preSnapped = snapped;
} else if (b.top < MARGINS) {
// hintTop();
setBounds(pane, 0, 0, window.innerWidth, window.innerHeight / 2);
preSnapped = snapped;
} else if (b.left < MARGINS) {
// hintLeft();
setBounds(pane, 0, 0, window.innerWidth / 2, window.innerHeight);
preSnapped = snapped;
} else if (b.right > rightScreenEdge) {
// hintRight();
setBounds(pane, window.innerWidth / 2, 0, window.innerWidth / 2, window.innerHeight);
preSnapped = snapped;
} else if (b.bottom > bottomScreenEdge) {
// hintBottom();
setBounds(pane, 0, window.innerHeight / 2, window.innerWidth, window.innerWidth / 2);
preSnapped = snapped;
} else {
preSnapped = null;
}
hintHide();
}
clicked = null;
}
Demo Testing link
Use sessionStorage or localStorage
I am trying to include this Codepen into a basic website for school.
The issue is that the code with a few tweaks, will not load locally. I have even put my entire website into Codepen as a test and it worked.
It should just be the cloth simulation and nothing else.
Here is the HTML and CSS in its smallest form.
<!doctype html>
<html>
<head>
<style>
body {
background: #2F4F4F;
}
#c {
display: block;
margin: 20px auto 0;
}
</style>
<meta charset="utf-8">
<title>Test</title>
<script type="text/javascript" src="Website/JavaScript/ClothSimulation.js"></script>
</head>
<body>
<canvas id="c"></canvas>
<div id="top">
<a id="close"></a>
</div>
</body>
</html>
The JS is very big as it is a cloth simulation.
document.getElementById('close').onmousedown = function(e) {
e.preventDefault();
document.getElementById('info').style.display = 'none';
return false;
};
// settings
var physics_accuracy = 3,
mouse_influence = 20,
mouse_cut = 5,
gravity = 1200,
cloth_height = 30,
cloth_width = 50,
start_y = 20,
spacing = 7,
tear_distance = 60;
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
var canvas,
ctx,
cloth,
boundsx,
boundsy,
mouse = {
down: false,
button: 1,
x: 0,
y: 0,
px: 0,
py: 0
};
var Point = function(x, y) {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.vx = 0;
this.vy = 0;
this.pin_x = null;
this.pin_y = null;
this.constraints = [];
};
Point.prototype.update = function(delta) {
if (mouse.down) {
var diff_x = this.x - mouse.x,
diff_y = this.y - mouse.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
if (mouse.button == 1) {
if (dist < mouse_influence) {
this.px = this.x - (mouse.x - mouse.px) * 1.8;
this.py = this.y - (mouse.y - mouse.py) * 1.8;
}
} else if (dist < mouse_cut) this.constraints = [];
}
this.add_force(0, gravity);
delta *= delta;
nx = this.x + ((this.x - this.px) * .99) + ((this.vx / 2) * delta);
ny = this.y + ((this.y - this.py) * .99) + ((this.vy / 2) * delta);
this.px = this.x;
this.py = this.y;
this.x = nx;
this.y = ny;
this.vy = this.vx = 0
};
Point.prototype.draw = function() {
if (!this.constraints.length) return;
var i = this.constraints.length;
while (i--) this.constraints[i].draw();
};
Point.prototype.resolve_constraints = function() {
if (this.pin_x != null && this.pin_y != null) {
this.x = this.pin_x;
this.y = this.pin_y;
return;
}
var i = this.constraints.length;
while (i--) this.constraints[i].resolve();
this.x > boundsx ? this.x = 2 * boundsx - this.x : 1 > this.x && (this.x = 2 - this.x);
this.y < 1 ? this.y = 2 - this.y : this.y > boundsy && (this.y = 2 * boundsy - this.y);
};
Point.prototype.attach = function(point) {
this.constraints.push(
new Constraint(this, point)
);
};
Point.prototype.remove_constraint = function(constraint) {
this.constraints.splice(this.constraints.indexOf(constraint), 1);
};
Point.prototype.add_force = function(x, y) {
this.vx += x;
this.vy += y;
};
Point.prototype.pin = function(pinx, piny) {
this.pin_x = pinx;
this.pin_y = piny;
};
var Constraint = function(p1, p2) {
this.p1 = p1;
this.p2 = p2;
this.length = spacing;
};
Constraint.prototype.resolve = function() {
var diff_x = this.p1.x - this.p2.x,
diff_y = this.p1.y - this.p2.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y),
diff = (this.length - dist) / dist;
if (dist > tear_distance) this.p1.remove_constraint(this);
var px = diff_x * diff * 0.5;
var py = diff_y * diff * 0.5;
this.p1.x += px;
this.p1.y += py;
this.p2.x -= px;
this.p2.y -= py;
};
Constraint.prototype.draw = function() {
ctx.moveTo(this.p1.x, this.p1.y);
ctx.lineTo(this.p2.x, this.p2.y);
};
var Cloth = function() {
this.points = [];
var start_x = canvas.width / 2 - cloth_width * spacing / 2;
for (var y = 0; y <= cloth_height; y++) {
for (var x = 0; x <= cloth_width; x++) {
var p = new Point(start_x + x * spacing, start_y + y * spacing);
x != 0 && p.attach(this.points[this.points.length - 1]);
y == 0 && p.pin(p.x, p.y);
y != 0 && p.attach(this.points[x + (y - 1) * (cloth_width + 1)])
this.points.push(p);
}
}
};
Cloth.prototype.update = function() {
var i = physics_accuracy;
while (i--) {
var p = this.points.length;
while (p--) this.points[p].resolve_constraints();
}
i = this.points.length;
while (i--) this.points[i].update(.016);
};
Cloth.prototype.draw = function() {
ctx.beginPath();
var i = cloth.points.length;
while (i--) cloth.points[i].draw();
ctx.stroke();
};
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
cloth.update();
cloth.draw();
requestAnimFrame(update);
}
function start() {
canvas.onmousedown = function(e) {
mouse.button = e.which;
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
mouse.down = true;
e.preventDefault();
};
canvas.onmouseup = function(e) {
mouse.down = false;
e.preventDefault();
};
canvas.onmousemove = function(e) {
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
e.preventDefault();
};
canvas.oncontextmenu = function(e) {
e.preventDefault();
};
boundsx = canvas.width - 1;
boundsy = canvas.height - 1;
ctx.strokeStyle = '#888';
cloth = new Cloth();
update();
}
window.onload = function() {
canvas = document.getElementById('c');
ctx = canvas.getContext('2d');
canvas.width = 560;
canvas.height = 350;
start();
};
Thank you for your help.
Assuming you have copy and pasted the website exactly how it is, you're missing opening and closing style tags around the CSS, and script tags around the JS.
Your code works, but you need this tags:
<script type="text/javascript"> YOUR JAVASCRIPT HERE </script>
<style type="text/css"> YOUR CSS HERE </style>
/*
Copyright (c) 2013 dissimulate at Codepen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
document.getElementById('close').onmousedown = function(e) {
e.preventDefault();
document.getElementById('info').style.display = 'none';
return false;
};
// settings
var physics_accuracy = 3,
mouse_influence = 20,
mouse_cut = 5,
gravity = 1200,
cloth_height = 30,
cloth_width = 50,
start_y = 20,
spacing = 7,
tear_distance = 60;
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
var canvas,
ctx,
cloth,
boundsx,
boundsy,
mouse = {
down: false,
button: 1,
x: 0,
y: 0,
px: 0,
py: 0
};
var Point = function(x, y) {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.vx = 0;
this.vy = 0;
this.pin_x = null;
this.pin_y = null;
this.constraints = [];
};
Point.prototype.update = function(delta) {
if (mouse.down) {
var diff_x = this.x - mouse.x,
diff_y = this.y - mouse.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
if (mouse.button == 1) {
if (dist < mouse_influence) {
this.px = this.x - (mouse.x - mouse.px) * 1.8;
this.py = this.y - (mouse.y - mouse.py) * 1.8;
}
} else if (dist < mouse_cut) this.constraints = [];
}
this.add_force(0, gravity);
delta *= delta;
nx = this.x + ((this.x - this.px) * .99) + ((this.vx / 2) * delta);
ny = this.y + ((this.y - this.py) * .99) + ((this.vy / 2) * delta);
this.px = this.x;
this.py = this.y;
this.x = nx;
this.y = ny;
this.vy = this.vx = 0
};
Point.prototype.draw = function() {
if (!this.constraints.length) return;
var i = this.constraints.length;
while (i--) this.constraints[i].draw();
};
Point.prototype.resolve_constraints = function() {
if (this.pin_x != null && this.pin_y != null) {
this.x = this.pin_x;
this.y = this.pin_y;
return;
}
var i = this.constraints.length;
while (i--) this.constraints[i].resolve();
this.x > boundsx ? this.x = 2 * boundsx - this.x : 1 > this.x && (this.x = 2 - this.x);
this.y < 1 ? this.y = 2 - this.y : this.y > boundsy && (this.y = 2 * boundsy - this.y);
};
Point.prototype.attach = function(point) {
this.constraints.push(
new Constraint(this, point)
);
};
Point.prototype.remove_constraint = function(constraint) {
this.constraints.splice(this.constraints.indexOf(constraint), 1);
};
Point.prototype.add_force = function(x, y) {
this.vx += x;
this.vy += y;
};
Point.prototype.pin = function(pinx, piny) {
this.pin_x = pinx;
this.pin_y = piny;
};
var Constraint = function(p1, p2) {
this.p1 = p1;
this.p2 = p2;
this.length = spacing;
};
Constraint.prototype.resolve = function() {
var diff_x = this.p1.x - this.p2.x,
diff_y = this.p1.y - this.p2.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y),
diff = (this.length - dist) / dist;
if (dist > tear_distance) this.p1.remove_constraint(this);
var px = diff_x * diff * 0.5;
var py = diff_y * diff * 0.5;
this.p1.x += px;
this.p1.y += py;
this.p2.x -= px;
this.p2.y -= py;
};
Constraint.prototype.draw = function() {
ctx.moveTo(this.p1.x, this.p1.y);
ctx.lineTo(this.p2.x, this.p2.y);
};
var Cloth = function() {
this.points = [];
var start_x = canvas.width / 2 - cloth_width * spacing / 2;
for (var y = 0; y <= cloth_height; y++) {
for (var x = 0; x <= cloth_width; x++) {
var p = new Point(start_x + x * spacing, start_y + y * spacing);
x != 0 && p.attach(this.points[this.points.length - 1]);
y == 0 && p.pin(p.x, p.y);
y != 0 && p.attach(this.points[x + (y - 1) * (cloth_width + 1)])
this.points.push(p);
}
}
};
Cloth.prototype.update = function() {
var i = physics_accuracy;
while (i--) {
var p = this.points.length;
while (p--) this.points[p].resolve_constraints();
}
i = this.points.length;
while (i--) this.points[i].update(.016);
};
Cloth.prototype.draw = function() {
ctx.beginPath();
var i = cloth.points.length;
while (i--) cloth.points[i].draw();
ctx.stroke();
};
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
cloth.update();
cloth.draw();
requestAnimFrame(update);
}
function start() {
canvas.onmousedown = function(e) {
mouse.button = e.which;
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
mouse.down = true;
e.preventDefault();
};
canvas.onmouseup = function(e) {
mouse.down = false;
e.preventDefault();
};
canvas.onmousemove = function(e) {
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
e.preventDefault();
};
canvas.oncontextmenu = function(e) {
e.preventDefault();
};
boundsx = canvas.width - 1;
boundsy = canvas.height - 1;
ctx.strokeStyle = '#888';
cloth = new Cloth();
update();
}
window.onload = function() {
canvas = document.getElementById('c');
ctx = canvas.getContext('2d');
canvas.width = 560;
canvas.height = 350;
start();
};
#charset "utf-8";
body {
line-height: 1.4;
font-size: 100%;
font-family: allerta;
margin-right: auto;
margin-left: auto;
margin-bottom: 0;
padding: 0;
color: #646464;
font-style: normal;
font-weight: 400;
background-color: #2F4F4F;
}
.center {
margin-bottom: 40px;
display: flex;
justify-content: center;
height: 50px;
padding-top: 132px;
}
.button-wrap {
margin-right: 25px;
top: 133px;
margin-top: -139px;
}
.rad-button {
white-space: nowrap;
border-radius: 4px;
position: relative;
border: none;
background: none;
font-family: allerta;
width: 200px;
height: 200px;
cursor: pointer;
transition: 0.1s all ease;
font-size: 32px;
font-weight: 400;
color: #777;
border-bottom: 1px solid #ccc;
box-shadow: 0px 0px 0px 0px #B8B8B8;
font-style: normal;
}
.rad-button.good {
background-color: #FAEBD7;
color: #2F4F4F;
border-bottom: 1px solid #759f87;
}
.rad-button.good:hover {
background-color: #caf3db;
top: -2px;
border-bottom: 4px solid #759f87;
box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.25);
}
.rad-button.good:active {
top: 0px;
border: 1px solid #759f87;
background-color: #a5dabc;
box-shadow: inset 0px 0px 4px rgba(0, 0, 0, 0.25);
}
.fade {
margin-top: 25px;
font-size: 21px;
text-align: center;
-webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
-moz-animation: fadein 2s; /* Firefox < 16 */
-ms-animation: fadein 2s; /* Internet Explorer */
-o-animation: fadein 2s; /* Opera < 12.1 */
animation: fadein 2s;
}
#keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Firefox < 16 */
#-moz-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Safari, Chrome and Opera > 12.1 */
#-webkit-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Internet Explorer */
#-ms-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Opera < 12.1 */
#-o-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
ul, ol, dl {
padding: 0;
margin: 0;
}
h1 {
font-size: 200%;
color: #FAEBD7;
font-weight: 400;
font-family: allerta;
font-style: normal;
text-align: center;
margin-left: -26px;
}
h2{
display: table-cell;
text-align: center;
vertical-align: middle;
color: #2F4F4F;
text-shadow: 0px 0px;
font-size: x-large;
}
h3, h4, h5, h6, p {
margin-top: 0;
padding-right: 15px;
padding-left: 15px;
color: #FAEBD7;
font-family: allerta;
font-style: normal;
font-weight: 400;
}
a img {
border: none;
}
a:link {
color: #FAEBD7;
text-decoration: none;
font-family: allerta;
font-style: normal;
font-weight: 400;
}
a:visited {
color: #6E6C64;
text-decoration: underline;
}
a:hover, a:active, a:focus {
text-decoration: none;
color: #CAF3DB;
font-family: allerta;
font-style: normal;
font-weight: 400;
text-align: center;
}
.container {
width: 960px;
background-color: #2F4F4F;
margin: 0 auto;
}
header {
background-color: #2F4F4F;
}
.sidebar1 {
float: right;
width: 180px;
background-color: #2F4F4F;
padding-bottom: 10px;
}
.content {
padding: 10px 0;
width: 780px;
display: inline;
top: 10px;
}
.content ul, .content ol {
padding: 0 15px 15px 40px;
}
nav ul{
list-style: none;
border-top: 1px solid #666;
margin-bottom: 15px;
}
nav li {
border-bottom: 1px solid #666;
}
nav a, nav a:visited {
padding: 5px 5px 5px 15px;
display: block;
width: 160px;
text-decoration: none;
background-color: #2F4F4F;
}
nav a:hover, nav a:active, nav a:focus {
background-color: #2F4F4F;
color: #FFF;
min-width: 0px;
top: 0px;
}
/* ~~ The footer ~~ */
footer {
padding: 10px 0;
background-color: #2F4F4F;
position: relative;
clear: both;
}
header, section, footer, aside, article, figure {
display: block;
color: #FAEBD7;
text-align: center;
left: -14px;
top: 134px;
}
#c {
display: block;
margin: 20px auto 0;
}
<html>
<head>
<meta charset="utf-8">
<title>Ewan Lyon Home</title>
<link href="../CSS/HTML5_twoColFixRtHdr.css" rel="stylesheet" type="text/css"><!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.-->
<script>var __adobewebfontsappname__="dreamweaver"</script>
<script src="http://use.edgefonts.net/allerta:n4:default.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<article class="content">
<h1>Ewan Lyon</h1>
<div class = "center">
<div class = "button-wrap">
<button class = "rad-button good flat">Photoshop</button>
</div>
<div class = "button-wrap">
<a href="Illustrator.html">
<button class = "rad-button good flat">Illustrator</button>
</a>
</div>
</div>
<div class = "center">
<div class = "button-wrap">
<button class = "rad-button good flat">About Me</button>
</div>
<div class = "button-wrap">
<button class = "rad-button good flat">RICE</button>
</div>
</div>
<script type="text/javascript" src="../JavaScript/ClothSimulation.js"></script>
<canvas id="c"></canvas>
<div id="top">
<a id="close"></a>
</div>
<footer>
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/80x15.png" /></a><br />Ewan Lyon
</footer>
</article>
</div>
</body>
</html>