JavaScript Resize, Drag, Snap with custom window/div size - javascript

I'm trying to figure out a way to resize/drag/snap a div element within a custom window/div size, not just the entire window. I had found this code here https://codepen.io/zz85/pen/gbOoVP which is exactly the functionality I'm looking for but I cannot figure out a way to adapt it to a custom bounding size. Currently it just takes the main windows bounds. Any help would be much appreciated. Thank you!
Here is the main Javascript code that I had found:
"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 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;
}

Related

want to style the all dots of pre built html canvas background

The code is different, I apologize may I didn't ask the question the right way, you can understand well in principle, When I'm hovering the dots get colours and connect to each other, other dots are invisible, I want that all dots should be visible all time. live example available on codepen, https://codepen.io/tati420/pen/RwBamQo?editors=1111
(function () {
var width,
height,
largeHeader,
canvas,
ctx,
points,
target,
animateHeader = true;
// Main
initHeader();
initAnimation();
addListeners();
function initHeader() {
width = window.innerWidth;
height = window.innerHeight;
target = { x: width / 2, y: height / 2 };
largeHeader = document.getElementById("large-header");
largeHeader.style.height = height + "px";
canvas = document.getElementById("demo-canvas");
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
// create points
points = [];
for (var x = 0; x < width; x = x + width / 20) {
for (var y = 0; y < height; y = y + height / 20) {
var px = x + (Math.random() * width) / 20;
var py = y + (Math.random() * height) / 20;
var p = { x: px, originX: px, y: py, originY: py };
points.push(p);
}
}
// for each point find the 5 closest points
for (var i = 0; i < points.length; i++) {
var closest = [];
var p1 = points[i];
for (var j = 0; j < points.length; j++) {
var p2 = points[j];
if (!(p1 == p2)) {
var placed = false;
for (var k = 0; k < 5; k++) {
if (!placed) {
if (closest[k] == undefined) {
closest[k] = p2;
placed = true;
}
}
}
for (var k = 0; k < 5; k++) {
if (!placed) {
if (getDistance(p1, p2) < getDistance(p1, closest[k])) {
closest[k] = p2;
placed = true;
}
}
}
}
}
p1.closest = closest;
}
// assign a circle to each point
for (var i in points) {
var c = new Circle(
points[i],
2 + Math.random() * 2,
"rgba(0,255,255,0.3)"
);
points[i].circle = c;
}
}
// Event handling
function addListeners() {
if (!("ontouchstart" in window)) {
window.addEventListener("mousemove", mouseMove);
}
window.addEventListener("scroll", scrollCheck);
window.addEventListener("resize", resize);
}
function mouseMove(e) {
var posx = (posy = 0);
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
} else if (e.clientX || e.clientY) {
posx =
e.clientX +
document.body.scrollLeft +
document.documentElement.scrollLeft;
posy =
e.clientY +
document.body.scrollTop +
document.documentElement.scrollTop;
}
target.x = posx;
target.y = posy;
}
function scrollCheck() {
if (document.body.scrollTop > height) animateHeader = false;
else animateHeader = true;
}
function resize() {
width = window.innerWidth;
height = window.innerHeight;
largeHeader.style.height = height + "px";
canvas.width = width;
canvas.height = height;
}
// animation
function initAnimation() {
animate();
for (var i in points) {
shiftPoint(points[i]);
}
}
function animate() {
if (animateHeader) {
ctx.clearRect(0, 0, width, height);
for (var i in points) {
// detect points in range
if (Math.abs(getDistance(target, points[i])) < 4000) {
points[i].active = 0.3;
points[i].circle.active = 0.6;
} else if (Math.abs(getDistance(target, points[i])) < 20000) {
points[i].active = 0.1;
points[i].circle.active = 0.3;
} else if (Math.abs(getDistance(target, points[i])) < 40000) {
points[i].active = 0.02;
points[i].circle.active = 0.1;
} else {
points[i].active = 0;
points[i].circle.active = 0;
}
drawLines(points[i]);
points[i].circle.draw();
}
}
requestAnimationFrame(animate);
}
function shiftPoint(p) {
TweenLite.to(p, 1 + 1 * Math.random(), {
x: p.originX - 50 + Math.random() * 100,
y: p.originY - 50 + Math.random() * 100,
ease: Circ.easeInOut,
onComplete: function () {
shiftPoint(p);
},
});
}
ctx.strokeStyle = "rgba(255,0,0," + p.active + ")";
// Canvas manipulation
function drawLines(p) {
if (!p.active) return;
for (var i in p.closest) {
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.closest[i].x, p.closest[i].y);
ctx.strokeStyle = "rgba(0,255,255," + p.active + ")";
ctx.stroke();
}
}
function Circle(pos, rad, color) {
var _this = this;
// constructor
(function () {
_this.pos = pos || null;
_this.radius = rad || null;
_this.color = color || null;
})();
this.draw = function () {
if (!_this.active) return;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgba(0,255,0," + _this.active + ")";
ctx.fill();
};
}
// Util
function getDistance(p1, p2) {
return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
}
})();
If I understand your question correctly, you just want to make sure that every point.active = 1 and point.circle.active = 1:
function animate() {
if (animateHeader) {
ctx.clearRect(0, 0, width, height);
for (var i in points) {
points[i].active = 1;
points[i].circle.active = 1;
drawLines(points[i]);
points[i].circle.draw();
}
}
requestAnimationFrame(animate);
}

How to stop multiple running mouse event functions

I want to resize squares drawn on canvas (created by clicking) with mouse by moving from corners. Should only resize selected square. I have four different functions for each corner, and after resizing from more than one corner functions keep executing. How to prevent this?
var isMouseDown = false;
var canvas;
var ctx, size;
$(document).ready(function() {
canvas = $('#area')[0];
ctx = canvas.getContext('2d');
$('#area').on('mousedown', canvasClick);
$('#area').on('mouseup', up);
});
function up(event) {
isMouseDown = false;
resizing = false;
console.log("up");
return;
}
function Square(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.isSelected = false;
}
var x, y;
function addSquare(event) {
x = event.pageX - canvas.offsetLeft;
y = event.pageY - canvas.offsetTop;
var size = parseInt(Math.random() * 81 + 49);
x -= size / 2;
y -= size / 2;
ctx.fillRect(x, y, size, size);
var square = new Square(x, y, size);
squares.push(square);
drawSquares();
}
var squares = new Array;
var previousSelectedSquare;
function drawSquares() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < squares.length; i++) {
var Square = squares[i];
ctx.beginPath();
ctx.fillStyle = "orange";
ctx.rect(Square.x, Square.y, Square.size, Square.size);
ctx.strokeStyle = "black";
if (Square.isSelected) {
ctx.lineWidth = 4;
} else {
ctx.lineWidth = 1;
}
ctx.fill();
ctx.stroke();
}
}
function canvasClick(event) {
isMouseDown = true;
x = event.pageX - canvas.offsetLeft;
y = event.pageY - canvas.offsetTop;
if (squares.length < 1) {
addSquare(event);
return;
}
var Square;
if (previousSelectedSquare) {
var prevX = previousSelectedSquare.x;
var prevY = previousSelectedSquare.y;
size = previousSelectedSquare.size;
}
var change = 7;
if (((x <= prevX + size + change) && (x >= prevX + size - change)) ||
((x >= prevX - change) && (x <= prevX + change)))
if (((y <= prevY + size + change) && (y >= prevY + size - change)) ||
((y <= prevY + change) && (y >= prevY - change))) {
console.log("borders");
$('#area').on('mousemove', resize(event));
return;
}
for (var i = squares.length - 1; i >= 0; i--) {
Square = squares[i];
if ((x >= Square.x && x <= Square.x + Square.size) && (y <= Square.y + Square.size && y >= Square.y)) {
Square.isSelected = true;
if (previousSelectedSquare != null)
previousSelectedSquare.isSelected = false;
if (previousSelectedSquare == Square)
previousSelectedSquare = null;
else
previousSelectedSquare = Square;
drawSquares();
return;
}
if (i === 0) {
addSquare(event);
return;
}
}
return;
}
// Part that resizes
var resizing = false;
function resize(event) {
if (!isMouseDown)
return;
resizing = true;
x = (event.pageX - canvas.offsetLeft);
y = (event.pageY - canvas.offsetTop);
size = previousSelectedSquare.size;
var centreX = previousSelectedSquare.x + size / 2;
var centreY = previousSelectedSquare.y + size / 2;
if (x > centreX && y < centreY) {
topr = true;
//top right
$('#area').on('mousemove', topR);
return;
}
if (x < centreX && y < centreY) {
//top left
$('#area').on('mousemove', topL);
return;
}
if (x > centreX && y > centreY) {
//bot right
$('#area').on('mousemove', botR);
return;
}
if (x < centreX && y > centreY) {
//bot left
$('#area').on('mousemove', botL);
return;
}
resizing = false;
return;
}
function topR(event) {
if (!resizing || !isMouseDown)
return;
$('#area').on('mouseup', up);
console.log("top right");
size = previousSelectedSquare.size;
var yb = previousSelectedSquare.y + size;
if (parseInt(yb - (event.pageY - canvas.offsetTop)) < 60)
return;
previousSelectedSquare.size = parseInt(yb - (event.pageY - canvas.offsetTop));
previousSelectedSquare.y = parseInt(event.pageY - canvas.offsetTop);
drawSquares();
return;
}
function topL(event) {
if (!resizing || !isMouseDown)
return;
$('#area').on('mouseup', up);
console.log("top left");
x = previousSelectedSquare.x + previousSelectedSquare.size;
y = previousSelectedSquare.y + previousSelectedSquare.size;
if (parseInt(y - (event.pageY - canvas.offsetTop)) < 60)
return;
previousSelectedSquare.size = parseInt(y - (event.pageY - canvas.offsetTop));
previousSelectedSquare.y = parseInt(event.pageY - canvas.offsetTop);
previousSelectedSquare.x = parseInt(event.pageX - canvas.offsetLeft);
drawSquares();
return;
}
function botR(event) {
if (!resizing || !isMouseDown)
return;
$('#area').on('mouseup', up);
console.log("bot right");
size = previousSelectedSquare.size;
if ((event.pageX - canvas.offsetLeft - previousSelectedSquare.x + size) / 2 < 60)
return;
previousSelectedSquare.size = parseInt((event.pageX - canvas.offsetLeft - previousSelectedSquare.x + size) / 2);
drawSquares();
return;
}
function botL(event) {
if (!resizing || !isMouseDown)
return;
$('#area').on('mouseup', up);
console.log("bot left");
var xr = previousSelectedSquare.x + previousSelectedSquare.size;
if (xr - event.pageX - canvas.offsetLeft < 60)
return;
previousSelectedSquare.size = parseInt(previousSelectedSquare.x + previousSelectedSquare.size - (event.pageX - canvas.offsetLeft));
previousSelectedSquare.x = parseInt(event.pageX - canvas.offsetLeft);
drawSquares();
return;
}
#area {
margin-top: 0;
border: 4px black solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="area" width="1250" height="550"></canvas>
Using namespace events, after you check the position, remove other handlers then add the one for the current corner.
e.g.: $('#area').off('mousemove.botR').off('mousemove.topL').off('mousemove.botL').on('mousemove.topR', topR);
var isMouseDown = false;
var canvas;
var ctx, size;
$(document).ready(function() {
canvas = $('#area')[0];
ctx = canvas.getContext('2d');
$('#area').on('mousedown', canvasClick);
$('#area').on('mouseup', up);
});
function up(event) {
isMouseDown = false;
resizing = false;
console.log("up");
return;
}
function Square(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.isSelected = false;
}
var x, y;
function addSquare(event) {
x = event.pageX - canvas.offsetLeft;
y = event.pageY - canvas.offsetTop;
var size = parseInt(Math.random() * 81 + 49);
x -= size / 2;
y -= size / 2;
ctx.fillRect(x, y, size, size);
var square = new Square(x, y, size);
squares.push(square);
drawSquares();
}
var squares = new Array;
var previousSelectedSquare;
function drawSquares() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < squares.length; i++) {
var Square = squares[i];
ctx.beginPath();
ctx.fillStyle = "orange";
ctx.rect(Square.x, Square.y, Square.size, Square.size);
ctx.strokeStyle = "black";
if (Square.isSelected) {
ctx.lineWidth = 4;
} else {
ctx.lineWidth = 1;
}
ctx.fill();
ctx.stroke();
}
}
function canvasClick(event) {
isMouseDown = true;
x = event.pageX - canvas.offsetLeft;
y = event.pageY - canvas.offsetTop;
if (squares.length < 1) {
addSquare(event);
return;
}
var Square;
if (previousSelectedSquare) {
var prevX = previousSelectedSquare.x;
var prevY = previousSelectedSquare.y;
size = previousSelectedSquare.size;
}
var change = 7;
if (((x <= prevX + size + change) && (x >= prevX + size - change)) ||
((x >= prevX - change) && (x <= prevX + change)))
if (((y <= prevY + size + change) && (y >= prevY + size - change)) ||
((y <= prevY + change) && (y >= prevY - change))) {
console.log("borders");
$('#area').on('mousemove', resize(event));
return;
}
for (var i = squares.length - 1; i >= 0; i--) {
Square = squares[i];
if ((x >= Square.x && x <= Square.x + Square.size) && (y <= Square.y + Square.size && y >= Square.y)) {
Square.isSelected = true;
if (previousSelectedSquare != null)
previousSelectedSquare.isSelected = false;
if (previousSelectedSquare == Square)
previousSelectedSquare = null;
else
previousSelectedSquare = Square;
drawSquares();
return;
}
if (i === 0) {
addSquare(event);
return;
}
}
return;
}
// Part that resizes
var resizing = false;
function resize(event) {
if (!isMouseDown)
return;
resizing = true;
x = (event.pageX - canvas.offsetLeft);
y = (event.pageY - canvas.offsetTop);
size = previousSelectedSquare.size;
var centreX = previousSelectedSquare.x + size / 2;
var centreY = previousSelectedSquare.y + size / 2;
if (x > centreX && y < centreY) {
topr = true;
//top right
$('#area').off('mousemove.botR').off('mousemove.topL').off('mousemove.botL').on('mousemove.topR', topR);
return;
}
if (x < centreX && y < centreY) {
//top left
$('#area').off('mousemove.topR').off('mousemove.botL').off('mousemove.botR').on('mousemove.topL', topL);
return;
}
if (x > centreX && y > centreY) {
//bot right
$('#area').off('mousemove.topR').off('mousemove.topL').off('mousemove.botL').on('mousemove.botR', botR);
return;
}
if (x < centreX && y > centreY) {
//bot left
$('#area').off('mousemove.topR').off('mousemove.topL').off('mousemove.botR').on('mousemove.botL', botL);
return;
}
resizing = false;
return;
}
function topR(event) {
if (!resizing || !isMouseDown)
return;
$('#area').on('mouseup', up);
console.log("top right");
size = previousSelectedSquare.size;
var yb = previousSelectedSquare.y + size;
if (parseInt(yb - (event.pageY - canvas.offsetTop)) < 60)
return;
previousSelectedSquare.size = parseInt(yb - (event.pageY - canvas.offsetTop));
previousSelectedSquare.y = parseInt(event.pageY - canvas.offsetTop);
drawSquares();
return;
}
function topL(event) {
if (!resizing || !isMouseDown)
return;
$('#area').on('mouseup', up);
console.log("top left");
x = previousSelectedSquare.x + previousSelectedSquare.size;
y = previousSelectedSquare.y + previousSelectedSquare.size;
if (parseInt(y - (event.pageY - canvas.offsetTop)) < 60)
return;
previousSelectedSquare.size = parseInt(y - (event.pageY - canvas.offsetTop));
previousSelectedSquare.y = parseInt(event.pageY - canvas.offsetTop);
previousSelectedSquare.x = parseInt(event.pageX - canvas.offsetLeft);
drawSquares();
return;
}
function botR(event) {
if (!resizing || !isMouseDown)
return;
$('#area').on('mouseup', up);
console.log("bot right");
size = previousSelectedSquare.size;
if ((event.pageX - canvas.offsetLeft - previousSelectedSquare.x + size) / 2 < 60)
return;
previousSelectedSquare.size = parseInt((event.pageX - canvas.offsetLeft - previousSelectedSquare.x + size) / 2);
drawSquares();
return;
}
function botL(event) {
if (!resizing || !isMouseDown)
return;
$('#area').on('mouseup', up);
console.log("bot left");
var xr = previousSelectedSquare.x + previousSelectedSquare.size;
if (xr - event.pageX - canvas.offsetLeft < 60)
return;
previousSelectedSquare.size = parseInt(previousSelectedSquare.x + previousSelectedSquare.size - (event.pageX - canvas.offsetLeft));
previousSelectedSquare.x = parseInt(event.pageX - canvas.offsetLeft);
drawSquares();
return;
}
#area {
margin-top: 0;
border: 4px black solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="area" width="1250" height="550"></canvas>

Auto-resize Canvas to Browser Width & Height

Disclaimer: very new to Javascript.
I'd like to make this canvas dynamically fit full width and height of the viewport, without the scaling present in CSS width/height declaration.
The original code can be found at Starfield animation done in HTML 5 .
After quite a few different attempts to affect this with the assistance of a number of stack answers, I've been unable to get the syntax right. Each different attempt breaks the rendering.
How can I go about this with such a complex function?
<!DOCTYPE html>
<html>
<head>
<title>Starfield Effect</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
border: 0;
overflow: hidden;
display: block;
background:#000;
}
</style>
<script>
window.onload = function() {
var starfieldCanvasId = "starfieldCanvas",
framerate = 60,
numberOfStarsModifier = 1.0,
flightSpeed = 0.02;
var canvas = document.getElementById(starfieldCanvasId),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
numberOfStars = width * height / 1000 * numberOfStarsModifier,
dirX = width / 2,
dirY = height / 2,
stars = [],
TWO_PI = Math.PI * 2;
for(var x = 0; x < numberOfStars; x++) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: range(0, 1)
};
}
canvas.onmousemove = function(event) {
dirX = event.offsetX,
dirY = event.offsetY;
}
window.setInterval(tick, Math.floor(1000 / framerate));
function tick() {
var oldX,
oldY;
// reset canvas for next frame
context.clearRect(0, 0, width, height);
for(var x = 0; x < numberOfStars; x++) {
// save old status
oldX = stars[x].x;
oldY = stars[x].y;
stars[x].x += (stars[x].x - dirX) * stars[x].size * flightSpeed;
stars[x].y += (stars[x].y - dirY) * stars[x].size * flightSpeed;
stars[x].size += flightSpeed;
if(stars[x].x < 0 || stars[x].x > width || stars[x].y < 0 || stars[x].y > height) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: 0
};
}
context.strokeStyle = "rgba(255, 255, 255, " + Math.min(stars[x].size, 1) + ")";
context.lineWidth = stars[x].size;
context.beginPath();
context.moveTo(oldX, oldY);
context.lineTo(stars[x].x, stars[x].y);
context.stroke();
}
}
function range(start, end) {
return Math.random() * (end - start) + start;
}
};
</script>
</head>
<body>
<canvas id="starfieldCanvas"></canvas>
</body>
</html>
Add a function
function TakeWholePageScreen() {
var myWidth = 0, myHeight = 0;
// source: http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
var starfieldCanvas = document.getElementById('starfieldCanvas');
starfieldCanvas.setAttribute('width',myWidth-20);
starfieldCanvas.setAttribute('height',myHeight-20);
}
Then add it at the top of the window.onload
window.onload = function() {
TakeWholePageScreen();
var starfieldCanvasId = "starfieldCanvas",
framerate = 60,
numberOfStarsModifier = 1.0,
flightSpeed = 0.02;
// ....
So the final version would look like this
<!DOCTYPE html>
<html>
<head>
<title>Starfield Effect</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
border: 0;
overflow: hidden;
display: block;
background:#000;
}
</style>
<script>
function TakeWholePageScreen() {
var myWidth = 0, myHeight = 0;
// source: http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
var starfieldCanvas = document.getElementById('starfieldCanvas');
starfieldCanvas.setAttribute('width',myWidth-20);
starfieldCanvas.setAttribute('height',myHeight-20);
}
window.onload = function() {
TakeWholePageScreen();
var starfieldCanvasId = "starfieldCanvas",
framerate = 60,
numberOfStarsModifier = 1.0,
flightSpeed = 0.02;
var canvas = document.getElementById(starfieldCanvasId),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
numberOfStars = width * height / 1000 * numberOfStarsModifier,
dirX = width / 2,
dirY = height / 2,
stars = [],
TWO_PI = Math.PI * 2;
for(var x = 0; x < numberOfStars; x++) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: range(0, 1)
};
}
canvas.onmousemove = function(event) {
dirX = event.offsetX,
dirY = event.offsetY;
}
window.setInterval(tick, Math.floor(1000 / framerate));
function tick() {
var oldX,
oldY;
// reset canvas for next frame
context.clearRect(0, 0, width, height);
for(var x = 0; x < numberOfStars; x++) {
// save old status
oldX = stars[x].x;
oldY = stars[x].y;
stars[x].x += (stars[x].x - dirX) * stars[x].size * flightSpeed;
stars[x].y += (stars[x].y - dirY) * stars[x].size * flightSpeed;
stars[x].size += flightSpeed;
if(stars[x].x < 0 || stars[x].x > width || stars[x].y < 0 || stars[x].y > height) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: 0
};
}
context.strokeStyle = "rgba(255, 255, 255, " + Math.min(stars[x].size, 1) + ")";
context.lineWidth = stars[x].size;
context.beginPath();
context.moveTo(oldX, oldY);
context.lineTo(stars[x].x, stars[x].y);
context.stroke();
}
}
function range(start, end) {
return Math.random() * (end - start) + start;
}
};
</script>
</head>
<body>
<canvas id="starfieldCanvas"></canvas>
</body>
</html>
:
<!DOCTYPE html>
<html>
<head>
<title>Starfield Effect</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
border: 0;
overflow: hidden;
display: block;
background:#000;
}
</style>
<script>
function TakeWholePageScreen() {
var myWidth = 0, myHeight = 0;
// source: http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
var starfieldCanvas = document.getElementById('starfieldCanvas');
starfieldCanvas.setAttribute('width',myWidth-20);
starfieldCanvas.setAttribute('height',myHeight-20);
}
window.onload = function() {
TakeWholePageScreen();
var starfieldCanvasId = "starfieldCanvas",
framerate = 60,
numberOfStarsModifier = 1.0,
flightSpeed = 0.02;
var canvas = document.getElementById(starfieldCanvasId),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
numberOfStars = width * height / 1000 * numberOfStarsModifier,
dirX = width / 2,
dirY = height / 2,
stars = [],
TWO_PI = Math.PI * 2;
for(var x = 0; x < numberOfStars; x++) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: range(0, 1)
};
}
canvas.onmousemove = function(event) {
dirX = event.offsetX,
dirY = event.offsetY;
}
window.setInterval(tick, Math.floor(1000 / framerate));
function tick() {
var oldX,
oldY;
// reset canvas for next frame
context.clearRect(0, 0, width, height);
for(var x = 0; x < numberOfStars; x++) {
// save old status
oldX = stars[x].x;
oldY = stars[x].y;
stars[x].x += (stars[x].x - dirX) * stars[x].size * flightSpeed;
stars[x].y += (stars[x].y - dirY) * stars[x].size * flightSpeed;
stars[x].size += flightSpeed;
if(stars[x].x < 0 || stars[x].x > width || stars[x].y < 0 || stars[x].y > height) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: 0
};
}
context.strokeStyle = "rgba(255, 255, 255, " + Math.min(stars[x].size, 1) + ")";
context.lineWidth = stars[x].size;
context.beginPath();
context.moveTo(oldX, oldY);
context.lineTo(stars[x].x, stars[x].y);
context.stroke();
}
}
function range(start, end) {
return Math.random() * (end - start) + start;
}
};
</script>
</head>
<body>
<canvas id="starfieldCanvas"></canvas>
</body>
</html>

Duplicate randomly multiple objects inside a javascript for loop

I found this platform game on the Internet and I modified it a bit:
<canvas id="canvas" widht=1000 height=400></canvas>
<script>
(function () {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 1000,
height = 400,
player = {
x: width / 2,
y: height - 15,
width: 5,
height: 5,
speed: 3,
velX: 0,
velY: 0,
jumping: false,
grounded: false
},
keys = [],
friction = 0.8,
gravity = 0.3;
var boxes = [];
// dimensions
a = Math.floor((Math.random() * 20) + 1);
for (i = 0; i < a; i++) {
random1 = Math.floor((Math.random() * 1000) + 1);
random2 = Math.floor((Math.random() * 400) + 1);
random3 = Math.floor((Math.random() * 200) + 1);
random4 = Math.floor((Math.random() * 200) + 1);
boxes.push({
x: random1,
y: random2,
width: random3,
height: random4
}
boxes.push({
x: 0,
y: 0,
width: 10,
height: height
});
boxes.push({
x: 0,
y: height - 2,
width: width,
height: 50
});
boxes.push({
x: width - 10,
y: 0,
width: 50,
height: height
});
canvas.width = width;
canvas.height = height;
function update() {
// check keys
if (keys[38] || keys[32]) {
// up arrow or space
if (!player.jumping && player.grounded) {
player.jumping = true;
player.grounded = false;
player.velY = -player.speed * 2;
}
}
if (keys[39]) {
// right arrow
if (player.velX < player.speed) {
player.velX++;
}
}
if (keys[37]) {
// left arrow
if (player.velX > -player.speed) {
player.velX--;
}
}
player.velX *= friction;
player.velY += gravity;
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "black";
ctx.beginPath();
player.grounded = false;
for (var i = 0; i < boxes.length; i++) {
ctx.rect(boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);
var dir = colCheck(player, boxes[i]);
if (dir === "l" || dir === "r") {
player.velX = 0;
player.jumping = false;
} else if (dir === "b") {
player.grounded = true;
player.jumping = false;
} else if (dir === "t") {
player.velY *= -1;
}
}
if(player.grounded){
player.velY = 0;
}
player.x += player.velX;
player.y += player.velY;
ctx.fill();
ctx.fillStyle = "red";
ctx.fillRect(player.x, player.y, player.width, player.height);
requestAnimationFrame(update);
}
function colCheck(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2),
colDir = null;
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
// figures out on which side we are colliding (top, bottom, left, or right)
var oX = hWidths - Math.abs(vX),
oY = hHeights - Math.abs(vY);
if (oX >= oY) {
if (vY > 0) {
colDir = "t";
shapeA.y += oY;
} else {
colDir = "b";
shapeA.y -= oY;
}
} else {
if (vX > 0) {
colDir = "l";
shapeA.x += oX;
} else {
colDir = "r";
shapeA.x -= oX;
}
}
}
return colDir;
}
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
window.addEventListener("load", function () {
update();
});
</script>
The problem is in the for loop when I want to create multiple boxes with random width, height, position but that didn't work. How could I do that?
In you code there are two syntax error. first one is you didn't close for loop and second one is inside for loop first push operation was not close properly.
i have update code.
(function () {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 1000,
height = 400,
player = {
x: width / 2,
y: height - 15,
width: 5,
height: 5,
speed: 3,
velX: 0,
velY: 0,
jumping: false,
grounded: false
},
keys = [],
friction = 0.8,
gravity = 0.3;
var boxes = [];
// dimensions
a = Math.floor((Math.random() * 20) + 1);
for (i = 0; i < a; i++) {
random1 = Math.floor((Math.random() * 1000) + 1);
random2 = Math.floor((Math.random() * 400) + 1);
random3 = Math.floor((Math.random() * 200) + 1);
random4 = Math.floor((Math.random() * 200) + 1);
boxes.push({
x: random1,
y: random2,
width: random3,
height: random4
});
boxes.push({
x: 0,
y: 0,
width: 10,
height: height
});
boxes.push({
x: 0,
y: height - 2,
width: width,
height: 50
});
boxes.push({
x: width - 10,
y: 0,
width: 50,
height: height
});
canvas.width = width;
canvas.height = height;
}
function update() {
// check keys
if (keys[38] || keys[32]) {
// up arrow or space
if (!player.jumping && player.grounded) {
player.jumping = true;
player.grounded = false;
player.velY = -player.speed * 2;
}
}
if (keys[39]) {
// right arrow
if (player.velX < player.speed) {
player.velX++;
}
}
if (keys[37]) {
// left arrow
if (player.velX > -player.speed) {
player.velX--;
}
}
player.velX *= friction;
player.velY += gravity;
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "black";
ctx.beginPath();
player.grounded = false;
for (var i = 0; i < boxes.length; i++) {
ctx.rect(boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);
var dir = colCheck(player, boxes[i]);
if (dir === "l" || dir === "r") {
player.velX = 0;
player.jumping = false;
} else if (dir === "b") {
player.grounded = true;
player.jumping = false;
} else if (dir === "t") {
player.velY *= -1;
}
}
if(player.grounded){
player.velY = 0;
}
player.x += player.velX;
player.y += player.velY;
ctx.fill();
ctx.fillStyle = "red";
ctx.fillRect(player.x, player.y, player.width, player.height);
requestAnimationFrame(update);
}
function colCheck(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2),
colDir = null;
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
// figures out on which side we are colliding (top, bottom, left, or right)
var oX = hWidths - Math.abs(vX),
oY = hHeights - Math.abs(vY);
if (oX >= oY) {
if (vY > 0) {
colDir = "t";
shapeA.y += oY;
} else {
colDir = "b";
shapeA.y -= oY;
}
} else {
if (vX > 0) {
colDir = "l";
shapeA.x += oX;
} else {
colDir = "r";
shapeA.x -= oX;
}
}
}
return colDir;
}
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
window.addEventListener("load", function () {
update();
});
<canvas id="canvas" widht=1000 height=400></canvas>

using querySelectorAll to move more than one div

I'm trying to use the queryselectorall to be able to move more than one div, but I'm getting trouble for not knowing how to adapt. I thought of using a while that style:
[].forEach.call(els, function(el) {
...
});
But not got success, how can I fix my script to make it work?
My code:
var draggableEl = document.querySelectorAll('[data-drag]'), magnet = document.querySelector('.magnet-zone');
function isOverlapping(el1, el2) {
var rect1 = el1.getBoundingClientRect(), rect2 = el2.getBoundingClientRect();
return !(rect1.top > rect2.bottom || rect1.right < rect2.left || rect1.bottom < rect2.top || rect1.left > rect2.right);
}
function moveToPos(x, y) {
var el = draggableEl;
el.style.transform = 'translate(' + Math.round(x, 10) + 'px, ' + Math.round(y, 10) + 'px) translateZ(0)';
el.style.webkitTransform = 'translate(' + Math.round(x, 10) + 'px, ' + Math.round(y, 10) + 'px) translateZ(0)';
}
function moveMagnet(x, y) {
var dist = 12, width = $('body').width() / 2, height = $('body').height(), direction = x > width ? 1 : -1, percX = x > width ? (x - width) / width : -(width - x) / width, percY = Math.min(1, (height - y) / (height / 2));
magnet.style.marginLeft = Math.round(dist / 1.5 * percX) + 'px';
magnet.style.marginBottom = Math.round(dist * percY) + 'px';
}
function move(event) {
var el = draggableEl, magnetRect = magnet.getBoundingClientRect(), elRect = el.getBoundingClientRect();
x = this._posOrigin.x + event.pageX - this._touchOrigin.x;
y = this._posOrigin.y + event.pageY - this._touchOrigin.y;
moveMagnet(x + elRect.width / 2, y + elRect.height / 2);
$('body').addClass('moving');
var touchPos = {
top: y,
right: x + elRect.width,
bottom: y + elRect.height,
left: x
};
overlapping = !(touchPos.top > magnetRect.bottom || touchPos.right < magnetRect.left || touchPos.bottom < magnetRect.top || touchPos.left > magnetRect.right);
if (overlapping) {
var mx = magnetRect.width / 2 + magnetRect.left;
var my = magnetRect.height / 2 + magnetRect.top;
x = mx - elRect.width / 2;
y = my - elRect.height / 2;
if (!$(el).hasClass('overlap')) {
$(el).addClass('transition');
setTimeout(function () {
$(el).removeClass('transition');
}, 150);
setTimeout(function () {
el.remove();
setTimeout(function () {
$('body').removeClass('moving touching');
}, 900);
}, 1000);
}
magnet.className = magnet.className.replace(' overlap', '') + ' overlap';
el.className = el.className.replace(' overlap', '') + ' overlap';
} else {
if ($(el).hasClass('transition')) {
$(el).removeClass('transition');
}
if ($(el).hasClass('overlap')) {
$(el).addClass('transition');
setTimeout(function () {
$(el).removeClass('transition');
}, 100);
}
magnet.className = magnet.className.replace(' overlap', '');
el.className = el.className.replace(' overlap', '');
}
moveToPos(x, y);
}
$(draggableEl).on('touchstart mousedown', onTouchStart).on('touchmove drag', move).on('touchend mouseup', onTouchEnd);
function onTouchStart(event) {
var rect = this.getBoundingClientRect();
$('body').addClass('touching');
$(this).removeClass('edge transition');
this._touchOrigin = {
x: event.pageX,
y: event.pageY
};
this._posOrigin = {
x: rect.left,
y: rect.top
};
}
function onTouchEnd(event) {
var el = draggableEl, rect = el.getBoundingClientRect(), width = $('body').width(), halfScreen = width / 2;
if (!$(el).hasClass('overlap')) {
$('body').removeClass('moving touching');
magnet.style.marginBottom = magnet.style.marginLeft = '0px';
var x = rect.left + rect.width / 2 < halfScreen ? +10 : width - 10 - rect.width;
$(el).addClass('edge');
moveToPos(x, rect.top);
setTimeout(function () {
$(el).removeClass('edge');
}, 500);
}
}
source: http://jsfiddle.net/4yt1roa6/

Categories

Resources