using querySelectorAll to move more than one div - javascript

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/

Related

How to add JavaScript file in angular cli application?

I am trying to replicate this effect - https://codepen.io/jonathasborges1/pen/YzryRpX in my angular app application.
But I'm having a hard time applying the effect
Someone can help me?
"use strict";
var LeafScene = function (el) {
this.viewport = el;
this.world = document.createElement("div");
this.leaves = [];
this.options = {
numLeaves: 60,
wind: {
magnitude: 1.2,
maxSpeed: 12,
duration: 300,
start: 0,
speed: 0
}
};
this.width = this.viewport.offsetWidth;
this.height = this.viewport.offsetHeight;
// animation helper
this.timer = 0;
this._resetLeaf = function (leaf) {
// place leaf towards the top left
leaf.x = this.width * 2 - Math.random() * this.width * 1.75;
leaf.y = -10;
leaf.z = Math.random() * 200;
if (leaf.x > this.width) {
leaf.x = this.width + 10;
leaf.y = (Math.random() * this.height) / 2;
}
// at the start, the leaf can be anywhere
if (this.timer == 0) {
leaf.y = Math.random() * this.height;
}
// Choose axis of rotation.
// If axis is not X, chose a random static x-rotation for greater variability
leaf.rotation.speed = Math.random() * 10;
var randomAxis = Math.random();
if (randomAxis > 0.5) {
leaf.rotation.axis = "X";
}
else if (randomAxis > 0.25) {
leaf.rotation.axis = "Y";
leaf.rotation.x = Math.random() * 180 + 90;
}
else {
leaf.rotation.axis = "Z";
leaf.rotation.x = Math.random() * 360 - 180;
// looks weird if the rotation is too fast around this axis
leaf.rotation.speed = Math.random() * 3;
}
// random speed
leaf.xSpeedVariation = Math.random() * 1 - 0.2;
leaf.ySpeed = Math.random();
return leaf;
};
this._updateLeaf = function (leaf) {
var leafWindSpeed = this.options.wind.speed(this.timer - this.options.wind.start, leaf.y);
var xSpeed = leafWindSpeed + leaf.xSpeedVariation;
leaf.x -= xSpeed;
leaf.y += leaf.ySpeed;
leaf.rotation.value += leaf.rotation.speed;
var t = "translateX( " +
leaf.x +
"px ) translateY( " +
leaf.y +
"px ) translateZ( " +
leaf.z +
"px ) rotate" +
leaf.rotation.axis +
"( " +
leaf.rotation.value +
"deg )";
if (leaf.rotation.axis !== "X") {
t += " rotateX(" + leaf.rotation.x + "deg)";
}
leaf.el.style.webkitTransform = t;
leaf.el.style.MozTransform = t;
leaf.el.style.oTransform = t;
leaf.el.style.transform = t;
// reset if out of view
if (leaf.x < -10 || leaf.y > this.height + 10) {
this._resetLeaf(leaf);
}
};
this._updateWind = function () {
if (this.timer === 0 ||
this.timer > this.options.wind.start + this.options.wind.duration) {
this.options.wind.magnitude = Math.random() * this.options.wind.maxSpeed;
this.options.wind.duration =
this.options.wind.magnitude * 50 + (Math.random() * 20 - 10);
this.options.wind.start = this.timer;
var screenHeight = this.height;
this.options.wind.speed = function (t, y) {
var a = ((this.magnitude / 2) * (screenHeight - (2 * y) / 3)) / screenHeight;
return (a *
Math.sin(((2 * Math.PI) / this.duration) * t + (3 * Math.PI) / 2) +
a);
};
}
};
};
LeafScene.prototype.init = function () {
for (var i = 0; i < this.options.numLeaves; i++) {
var leaf = {
el: document.createElement("div"),
x: 0,
y: 0,
z: 0,
rotation: {
axis: "X",
value: 0,
speed: 0,
x: 0
},
xSpeedVariation: 0,
ySpeed: 0,
path: {
type: 1,
start: 0
},
image: 1
};
this._resetLeaf(leaf);
this.leaves.push(leaf);
this.world.appendChild(leaf.el);
}
this.world.className = "leaf-scene";
this.viewport.appendChild(this.world);
// reset window height/width on resize
var self = this;
window.onresize = function (event) {
self.width = self.viewport.offsetWidth;
self.height = self.viewport.offsetHeight;
};
};
LeafScene.prototype.render = function () {
this._updateWind();
for (var i = 0; i < this.leaves.length; i++) {
this._updateLeaf(this.leaves[i]);
}
this.timer++;
requestAnimationFrame(this.render.bind(this));
};
// start up leaf scene
var leafContainer = document.querySelector(".falling-leaves"), leaves = new LeafScene(leafContainer);
leaves.init();
leaves.render();
You can create a file like <script> ..that js code.. </script> and save it as script.js and then add it to your index.html or dynamicly load it:
public loadScript(){
return new Promise(resolve => {
const scriptElement = document.createElement('script');
scriptElement.src = '/assets/js/script.js'
scriptElement.onload = resolve;
document.body.appendChild(scriptElement);
});
}
and then call and subscribe this function in your ts file to know when it is loaded or do something when its loaded in your page.

I can't delete dom element 'img' in onclick function of Object

I write a simple bubble game(I create Array and he has bubble Objects) and Bubble has to burst, when I click it(so I delete dom img), but i can't apply to dom elemnt in function onclick. Why? How can I apply to my dom element(IMG) or how can I delete dom img in func onclick????
My Object "bubble"
enter image description here
Google Chrome Inspector write...enter image description here
Full Code:
function resize() {
Grass.width = document.documentElement.clientWidth;
Grass.style.left = 0 + 'px';
Grass.style.top = document.documentElement.clientHeight - 180 + 'px';
}
function bubble(id) {
this.IMG = document.createElement('img');
this.IMG.src = './bubble.png';
this.IMG.id = id;
this.IMG.onclick = function () {
document.getElementById(this.IMG.id).parentNode.removeChild(document.getElementById(this.IMG.id));
}
this.createBubble = function () {
this.bubbleSize = Math.random() * (144 - 30) + 30;
this.bomDiapozon = Math.random() * (75 - 55) + 55;
this.IMG.style.width = this.bubbleSize + 'px';
this.IMG.style.height = this.bubbleSize + 'px';
this.xStart = Math.random() * document.documentElement.clientWidth;
this.yStart = -Math.random() * document.documentElement.clientHeight;
this.x = this.xStart;
this.y = this.yStart;
this.xSpeed = Math.random() * (9 + 9) - 9;
this.ySpeed = Math.random() * (5 - 1) + 1;
this.flyWidth = Math.random() * (288 - 144) + 144;
}
this.createBubble();
document.body.appendChild(this.IMG);
this.fly = function () {
if (this.y + this.bubbleSize >= document.documentElement.clientHeight - this.bomDiapozon) {
this.createBubble();
}
if ((this.x >= this.xStart + this.flyWidth / 2) || (this.x <= this.xStart - this.flyWidth / 2)) {
this.xSpeed = -this.xSpeed;
}
this.IMG.style.left = this.x + 'px';
this.IMG.style.top = this.y + 'px';
this.x += this.xSpeed;
this.y += this.ySpeed;
}
}
function go() {
for (var i = 0; i < amountBubbles; i++) {
bubbles[i].fly();
}
}
document.body.style.overflow = 'hidden';
var amountBubbles = 30;
var bubbles = [];
for (var i = 0; i < amountBubbles; i++) {
bubbles[i] = new bubble(i + 1);
}
var Grass = document.createElement('img');
Grass.src = './Grass.png';
document.body.appendChild(Grass);
resize();
setInterval(go, 40);
img {
position:absolute;
}
You already have access to the event and node without needing to re-select it. Try this:
this.IMG.onclick = function(event) {
var parent = event.target.parentElement;
parent.removeChild(event.target)
}
Welcome to Stalk Overflow!
In your anonymous function there is no context to this.
The snippet below binds this to that function, and it will be no longer undefined:
this.IMG.onclick = (function () {
document.getElementById(this.IMG.id).parentNode.removeChild(document.getElementById(this.IMG.id));
}).bind(this)
Just notice how you wrap it with () and then add .bind(this) to it.
Another way to bind the context is by using an arrow function:
this.IMG.onclick = () => {
document.getElementById(this.IMG.id).parentNode.removeChild(document.getElementById(this.IMG.id));
}
This arrow function binds this, arguments and super to your method.
Read more on arrow functions here
See it working below with .bind(this):
function resize() {
Grass.width = document.documentElement.clientWidth;
Grass.style.left = 0 + 'px';
Grass.style.top = document.documentElement.clientHeight - 180 + 'px';
}
function bubble(id) {
this.IMG = document.createElement('img');
this.IMG.src = './bubble.png';
this.IMG.id = id;
this.IMG.onclick = (function () {
document.getElementById(this.IMG.id).parentNode.removeChild(document.getElementById(this.IMG.id));
}).bind(this)
this.createBubble = function () {
this.bubbleSize = Math.random() * (144 - 30) + 30;
this.bomDiapozon = Math.random() * (75 - 55) + 55;
this.IMG.style.width = this.bubbleSize + 'px';
this.IMG.style.height = this.bubbleSize + 'px';
this.xStart = Math.random() * document.documentElement.clientWidth;
this.yStart = -Math.random() * document.documentElement.clientHeight;
this.x = this.xStart;
this.y = this.yStart;
this.xSpeed = Math.random() * (9 + 9) - 9;
this.ySpeed = Math.random() * (5 - 1) + 1;
this.flyWidth = Math.random() * (288 - 144) + 144;
}
this.createBubble();
document.body.appendChild(this.IMG);
this.fly = function () {
if (this.y + this.bubbleSize >= document.documentElement.clientHeight - this.bomDiapozon) {
this.createBubble();
}
if ((this.x >= this.xStart + this.flyWidth / 2) || (this.x <= this.xStart - this.flyWidth / 2)) {
this.xSpeed = -this.xSpeed;
}
this.IMG.style.left = this.x + 'px';
this.IMG.style.top = this.y + 'px';
this.x += this.xSpeed;
this.y += this.ySpeed;
}
}
function go() {
for (var i = 0; i < amountBubbles; i++) {
bubbles[i].fly();
}
}
document.body.style.overflow = 'hidden';
var amountBubbles = 30;
var bubbles = [];
for (var i = 0; i < amountBubbles; i++) {
bubbles[i] = new bubble(i + 1);
}
var Grass = document.createElement('img');
Grass.src = './Grass.png';
document.body.appendChild(Grass);
resize();
setInterval(go, 40);
img {
position:absolute;
}

How to zoom image with angularJS

How can i zoom the image when i click on the image itself using angularJS. I cant happen to do it when i using this website given: https://github.com/owlsomely/angular-image-zoom?utm_source=angular-js.in&utm_medium=website&utm_campaign=content-curation . Anyone can help?
My js file:
var camListApp = angular.module('camListApp', ['ui.bootstrap'])
camListApp.filter('unique', function() {
return function(input, key) {
var unique = {};
var uniqueList = [];
for(var i = 0; i < input.length; i++){
if(typeof unique[input[i][key]] == "undefined"){
unique[input[i][key]] = "";
uniqueList.push(input[i]);
}
}
return uniqueList;
};
});
camListApp.controller("Hello", ["$scope", "$http", function($scope, $http){
$scope.custom = true;
$scope.toggleCustom = function(url) {
$scope.custom = ! $scope.custom;
$scope.imageView = url;
};
$http.get('http://localhost:8082/camera/list').then(function(response) {
console.log(response);
$scope.records= response.data;
});
}]);
My html file:
<div ng-controller="Hello" class="col-xs-12">
<b>Search:</b><br>
<input type = "text" ng-model="searchBox" uib-typeahead="state.cameraid as state.cameraid for state in records | filter:searchBox | limitTo:8 | unique:'cameraid'">
<br>
<br>
<br>
<br>
<table border = 1 class="table table-striped table-hover" style="width:45%">
<thead>
<tr>
<th><center>CamID</th></center>
<th><center>Timestamp</th></center>
<th><center>View Image</center></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="record in records | filter:searchBox | orderBy:'+timestamp'">
<td>{{record.cameraid}}</td>
<td>{{record.timestamp}}</td>
<td><center> <button class="btn btn-primary" ng-click="toggleCustom(record.filename)" onclick="myFunction()">View</center></button></td>
</tr>
</tbody>
</table>
<span id="myDIV" ng-hide="custom">
<img ng-src="http://localhost:9100/Images/{{imageView}}.png" image-zoom width="500" height="400">
</span>
<!--<span ng-hide="custom">To:
<input type="text" id="to" />
</span>-->
<span ng-show="custom"></span>
</div>
<script>
function myFunction() {
document.getElementById("myDIV").style.position = "absolute";
}
</script>
</body>
</html>
Created ng-click on image
HTML
<span id="myDIV" ng-hide="custom">
<img id="view" ng-src="http://www.w3schools.com/css/{{imageView}}" width="300" height="300" ng-click="zoom()">
</span>
JS
$scope.zoom = function() {
var imageId = document.getElementById('view');
if(imageId.style.width == "400px"){
imageId.style.width = "300px";
imageId.style.height = "300px";
}else{
imageId.style.width = "400px";
imageId.style.height = "400px";
}
Codepen- http://codepen.io/nagasai/pen/jrMzER
my simple directive to increase the image reduction and image movement. I hope will be useful to you.
(function () {
angular
.module('app')
.directive('zoom', [function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
var img = elem[0];
$(img).css({
"position": "absolute",
"top": "0",
"bottom": "0",
"left": "0",
"right": "0",
"margin": "auto",
"padding-left": "1px",
"padding-right": "1px",
"padding-top": "1px",
"padding-bottom": "1px",
"-webkit - user - select": "none",
"-webkit - user - drag": "none"
});
var imageContainer = img.parentNode.parentNode;
$(imageContainer).css({
"text-align": "center",
"margin": "0",
"padding": "0",
"height": "100%",
"max- height": "100%",
"width": "100%",
"background-color": "#000",
"overflow": "hidden",
"-webkit - user - select": "none",
"cursor": "context - menu",
});
var parent = img.parentNode;
$(parent).css({
"width": "100%",
"height": "auto",
"margin": 0,
"padding": 0,
"display": "-webkit - box",
"-webkit - box - pack": "center",
"-webkit - box - align": "center",
"z-index": "5"
});
var currentScale = 1;
var currentRotation = 90
let transformOriginX = 0, transformOriginY = 0;
let translateX = 0, translateY = 0;
function setTransformOrigin() {
let imgRect = img.getBoundingClientRect();
let parentRect = parent.getBoundingClientRect();
let visibleWidth = (imgRect.width > parent.offsetWidth) ? imgRect.left + parentRect.width : imgRect.width;
let visibleHeight = (imgRect.height > parent.offsetHeight) ? imgRect.top + parentRect.height : imgRect.height;
let beginX = parentRect.right - visibleWidth, beginY = parentRect.bottom - visibleHeight;
let endX = beginX + visibleWidth, endY = beginY + visibleHeight;
let midX = beginX + ((endX - beginX) / 2), midY = beginY + ((endY - beginY) / 2);
// if (midY > imageContainer.clientHeight / 2) midY = imageContainer.clientHeight / 2;
//if (midX > imageContainer.clientWidth / 2) midX = imageContainer.clientWidth / 2;
if (midY > imageContainer.clientHeight / 2) { parent.style.transformOrigin = midX + 'px ' + midY + 'px' } else {
parent.style.transformOrigin = midX + 'px ' + imageContainer.clientHeight / 2 + 'px'
}
}
function scaleImage(scale, event) {
img.style.transform = 'scale(' + scale + ') ' + 'rotate(' + (currentRotation - 90) + 'deg)';
if (scale < currentScale) {
let imgRect = img.getBoundingClientRect();
let imageContainerRect = imageContainer.getBoundingClientRect();
if (parent.style.transform.match('translate')) {
let parentTransform = parent.style.transform.replace('translate(', '').replace(')', '').split(', ');
let moveX = parentTransform[0].replace('px', ''), moveY = parentTransform[1].replace('px', '');
if ((imageContainerRect.right - imgRect.right) > 0 || (imageContainerRect.left - imgRect.left) < 0) {
let moveBy = ((imageContainerRect.right - imgRect.right) > 0) ? (imageContainerRect.right - imgRect.right) : (imageContainerRect.left - imgRect.left);
moveX = (imgRect.width > parent.offsetWidth) ? (parseFloat(parentTransform[0]) + moveBy) : 0;
transformOriginX = (transformOriginX - moveBy);
}
if ((imageContainerRect.bottom - imgRect.bottom) > 0 || (imageContainerRect.top - imgRect.top) < 0) {
let moveBy = ((imageContainerRect.bottom - imgRect.bottom) > 0) ? (imageContainerRect.bottom - imgRect.bottom) : (imageContainerRect.top - imgRect.top);
moveY = (imgRect.height > parent.offsetHeight) ? (parseFloat(parentTransform[1]) + moveBy) : 0;
transformOriginY = (transformOriginY + moveBy);
}
if (scale <= 1) { translateX = 0; translateY = 0; }
parent.style.transformOrigin = transformOriginX + 'px ' + transformOriginY + 'px';
}
}
currentScale = scale;
let imgRect = img.getBoundingClientRect();
let parentRect = parent.getBoundingClientRect();
let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
let startX = event.pageX - translateX, startY = event.pageY - translateY;
let max_left = parentRect.left - imgRect.left;
let max_top = parentRect.top - imgRect.top;
var evt = window.event;
translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
if ((translateX != 0) && (translateY != 0)) {
if (translateY > imageContainer.clientHeight/2) { parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)' } else {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+'px)'
}
} else {
parent.style['-webkit-transform'] = ''
};
return false;
}
function tap() {
let imgRect = img.getBoundingClientRect();
let parentRect = parent.getBoundingClientRect();
let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
let startX = event.pageX - translateX, startY = event.pageY - translateY;
let max_left = parentRect.left - imgRect.left;
let max_top = parentRect.top - imgRect.top;
var evt = window.event;
translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
if ((translateX != 0) && (translateY != 0)) {
if (translateY > imageContainer.clientHeight / 2) {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)'
} else {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+ 'px)'
}
} else {
parent.style['-webkit-transform'] = ''
};
}
function makeDraggable(event) {
parent = img.parentNode;
imageContainer = img.parentNode.parentNode;
$(parent).css({
"display": "-webkit - box",
"-webkit - box - pack": "center",
"-webkit - box - align": "center",
"z-index": "5"
});
$(imageContainer).css({
"text-align": "center",
"margin": "0",
"padding": "0",
"overflow": "hidden",
"-webkit - user - select": "none",
"cursor": "context - menu",
});
let imgRect = img.getBoundingClientRect();
let parentRect =parent.getBoundingClientRect();
let overflow_horizontal = (imgRect.width > parent.offsetWidth ? true : false);
let overflow_vertical = (imgRect.height > parent.offsetHeight ? true : false);
let startX = event.pageX - translateX, startY = event.pageY - translateY;
let max_left = parentRect.left - imgRect.left;
let max_top = parentRect.top - imgRect.top;
window.onmousemove = function (evt) {
if (evt == null) { evt = window.event; }
translateX = (Math.abs(evt.pageX - startX) >= max_left ? (max_left * Math.sign(evt.pageX - startX)) : (evt.pageX - startX));
translateY = (Math.abs(evt.pageY - startY) >= max_top ? (max_top * Math.sign(evt.pageY - startY)) : (evt.pageY - startY));
translateX = overflow_horizontal ? translateX : 0, translateY = overflow_vertical ? translateY : 0;
if ((translateX != 0) && (translateY != 0)) {
if (translateY > imageContainer.clientHeight) {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + translateY + 'px)'
} else {
parent.style['-webkit-transform'] = 'translate(' + translateX + 'px, ' + imageContainer.clientHeight / 2+ 'px)'
}
} else {
parent.style['-webkit-transform'] = ''
};
return false;
}
window.onmouseup = function (evt) {
setTransformOrigin();
window.onmousemove = null;
}
return false;
};
img.addEventListener('mousedown', function () { makeDraggable(event); });
elem.bind('mousewheel', function (e) {
var img = e.currentTarget.style.width;
var scaleX = e.currentTarget.getBoundingClientRect().width / e.currentTarget.offsetWidth;
var w = "";
var resW = "";
var resL = "";
var resT = "";
var zValue = 1.2;
var newScale = scaleX * zValue;
var newScale = "scale(1)";
var val = parseInt(w.replace('%', ''));
if (e.originalEvent.wheelDelta / 120 > 0) {
newScale = scaleX * zValue;
}
else {
if ((scaleX / zValue) > 1) {
newScale = scaleX / zValue
} else {
newScale = 1.0;
}
}
scaleImage(newScale, e);
setTransformOrigin();
window.onmousemove = null;
});
}
}
}]);
})();
Use at HTML as
<image zoom src="" ></image>

Why isn't the location of my img not changing past 10px?

I want an img to follow the mouse, but it doesn't seem to do it.
It stops after it moves 10px.
I don't know why it's not working. When I set the position of the img to the position of the mouse, it works.
var elem = document.getElementById("img").style;
var IE = document.all ? true : false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
var tempX;
var tempY;
function getMouseXY(e) {
if (IE) {
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
} else {
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0) {
tempX = 0;
}
if (tempY < 0) {
tempY = 0;
}
document.Show.MouseX.value = tempX;
document.Show.MouseY.value = tempY;
return true;
}
document.onmousemove = getMouseXY;
document.onmouseover = update;
elem.left = "0px";
elem.bottom = "0px";
elem.position = "relative";
function update() {
if (parseInt(elem.left) < (tempX - 10)) {
elem.left = (parseInt(elem.left) + 1, 10).toString() + "px";
console.log((parseInt(elem.left) + 1, 10).toString() + "px");
}
if (parseInt(elem.left) > (tempX - 10)) {
elem.left = (parseInt(elem.left) - 1, 10).toString() + "px";
console.log((parseInt(elem.left) - 1, 10).toString() + "px");
}
if (parseInt(elem.bottom) < (-tempY + 50)) {
elem.bottom = (parseInt(elem.bottom) + 1, 10).toString() + "px";
console.log((parseInt(elem.left) + 1, 10).toString() + "px");
}
if (parseInt(elem.bottom) > (-tempY + 50)) {
elem.bottom = (parseInt(elem.bottom) - 1, 10).toString() + "px";
console.log((parseInt(elem.left) + 1, 10).toString() + "px");
}
}
<img id="img" src="//placehold.it/20.png">

Javascript/HTML Canvas Issues in Chrome/Firefox (Not Safari)

When I run this script on Safari, everything works fine. However when I open it up in Chrome or Firefox it does not execute correctly. In the Chrome console it says that there are Uncaught type errors for:
ctx.drawImage(img, x + 1, y + 1, iwh, iwh);
and
function renderStarField() {
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
for (var i = 0; i < stars.length; i++) {
stars[i].plot();
}
}
Here is my entire script, thanks for the help!
<script type="text/javascript">
var starField = (function () {
var browserWIDTH = $(document).width(),
browserHEIGHT = $(document).height(),
WIDTH = browserWIDTH + 500,
HEIGHT = 400,
FIELD_DEPTH = 15,
DISTANCE = 500,
STAR_DIAMETER = 45,
STAR_SPEED = 0.003,
canvas,
ctx,
numStars = 2000,
stars = [];
function Star() {
this.calcPosition();
var RANDSTAR = Math.floor(Math.random() * 3) + 1;
}
Star.prototype.calcPosition = function (reset) {
this.x = this.randomise(-25, 50);
this.y = this.randomise(-25, 50);
this.z = reset ? FIELD_DEPTH : this.randomise(1, FIELD_DEPTH);
};
Star.prototype.randomise = function (min, max) {
return Math.floor((Math.random() * max) + min);
};
Star.prototype.plot = function () {
//calculate 3d to 2d using perspective projection with the screen as the origin
var x = this.x * (DISTANCE / this.z) + WIDTH / 2,
y = this.y * (DISTANCE / this.z) + HEIGHT / 2;
if ((x >= 0 && x <= WIDTH) && (y >= 0 && y <= HEIGHT)) {
ctx.beginPath();
var img = document.createElement('image');
img.src ='Star1.png';
var iwh = this.calcSize(this.z);
ctx.moveTo(x, y);
ctx.drawImage(img, x + 1, y + 1, iwh, iwh);
}
this.z -= STAR_SPEED;
if (this.z <= 0) {
this.calcPosition(true);
}
};
Star.prototype.calcColor = function (z) {
var rgb = Math.abs((z * 5) - 255).toFixed(0),
a = (1 - ((z / (FIELD_DEPTH / 100)) / 100)).toFixed(1);
return 'rgba(' + rgb + ', ' + rgb + ', ' + rgb + ', ' + a + ')';
};
Star.prototype.calcSize = function (z) {
return Math.abs(((z / (FIELD_DEPTH / 100)) * (STAR_DIAMETER / 100)) - STAR_DIAMETER);
};
function setUpCanvas() {
canvas = document.querySelector('#stage');
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext('2d');
}
function buildStars() {
for (var i = 0; i < numStars; i++) {
stars.push(new Star());
}
}
function renderStarField() {
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
for (var i = 0; i < stars.length; i++) {
stars[i].plot();
}
}
function initialise() {
setUpCanvas();
buildStars();
setInterval(renderStarField, 20);
}
return {
init: initialise
}
})();
document.addEventListener('DOMContentLoaded', function () {
starField.init();
});
</script>
if ((x >= 0 && x <= WIDTH) && (y >= 0 && y <= HEIGHT)) {
ctx.beginPath();
var img = document.createElement('image');
img.src ='Star1.png';
var iwh = this.calcSize(this.z);
ctx.moveTo(x, y);
ctx.drawImage(img, x + 1, y + 1, iwh, iwh);
}
This code has some error
img.src = 'Star1.png' is not working, try img.setAttribute('src','Star1.png');
and Create <img> tag code is not document.createElement('image')
try document.createElement('img');
Change To
if ((x >= 0 && x <= WIDTH) && (y >= 0 && y <= HEIGHT)) {
ctx.beginPath();
var img = document.createElement('img');
img.setAttribute('src','Star1.png');
var iwh = this.calcSize(this.z);
ctx.moveTo(x, y);
ctx.drawImage(img, x + 1, y + 1, iwh, iwh);
}

Categories

Resources