Adding resize functionality to an element in angular - javascript

I am adding a resize functionality following a codepen example
mentioned in the comments using MARGIN=4 (here I was not able to add the codepen link)
The codepen was the best working example which I could find.
Have added 4 elements on all the 4 edges of the box.
I Have added hostlisteners to pointerdown , pointermove and pointerup but I am stuck with executing the animate() function present in Resizable directive.
In the directive the code has mainly 3 functions doing all the calculations onDown() , calc(e), animate()
import { Directive,
ElementRef,
HostListener } from '#angular/core';
import { DraggableDirective } from './draggable.directive';
#Directive({
selector: '[appResizable]' // Attribute selector
})
export class ResizableDirective extends DraggableDirective{
constructor(public element:ElementRef){
super(element);
}
minWidth = 60;
minHeight = 40;
// Thresholds
MARGINS = 4;
//End Of whats configurable
clicked = null;
public onRightEdge; onBottomEdge; onLeftEdge; onTopEdge;
public b; x; y;
redraw = false;
e;
clickedDragging = false;
ngOnInit(){
this.animate()
}
#HostListener('dragStart', ['$event'])
onDragStart(e:PointerEvent): void{
this.clickedDragging = true;
this.onDown(e);
e.preventDefault();
}
#HostListener('dragMove', ['$event'])
onDragMove(ee): void{
if (!this.dragging || ee.pointerId !== this.pointerId) {
return;
}
if((<HTMLElement>event.srcElement).id === ('side-top')){
this.onMove(ee);
ee.preventDefault();
}
}
#HostListener('dragEnd', ['$event'])
ondragend(ev): void{
this.onUp(ev);
}
onMove(ee){
if (!this.dragging || ee.pointerId !== this.pointerId) {
return;
}
if(this.clickedDragging){
this.calc(ee);
this.e = ee;
this.redraw = true;
}
}
onDown(e){
this.calc(e);
let isResizing = this.onRightEdge || this.onBottomEdge ||
this.onLeftEdge || this.onTopEdge;
this.clicked = {
x: this.x,
y: this.y,
cx: e.clientX,
cy: e.clientY,
w: this.b.width,
h: this.b.height,
isResizing: isResizing,
onRightEdge: this.onRightEdge,
onBottomEdge: this.onBottomEdge,
onLeftEdge: this.onLeftEdge,
onTopEdge: this.onTopEdge,
}
}
calc(e){
this.b = this.element.nativeElement.getBoundingClientRect();
this.x = e.clientX - this.b.left;
this.y = e.clientY - this.b.top;
this.onRightEdge = this.x >= this.b.width - this.MARGINS;
this.onBottomEdge = this.y >= this.b.height - this.MARGINS;
this.onLeftEdge = this.x < this.MARGINS;
this.onTopEdge = this.y < this.MARGINS;
}
animate(){
requestAnimationFrame(this.animate);
if(!this.redraw)return;
this.redraw = false;
if(this.clicked && this.clicked.isResizing){
if(this.clicked.onRightEdge){
this.element.nativeElement.style.width = Math.max(this.x,
this.minWidth) + 'px';
}
if(this.clicked.onBottomEdge){
this.element.nativeElement.style.height = Math.max(this.y,
this.minHeight) + 'px';
}
if(this.clicked.onLeftEdge){
let currentWidth = Math.max(this.clicked.cx -
this.e.clientX + this.clicked.w, this.minWidth);
if(currentWidth > this.minWidth){
this.element.nativeElement.style.width = currentWidth + 'px';
this.element.nativeElement.style.left = this.e.clientX + 'px';
}
}
if (this.clicked.onTopEdge) {
var currentHeight = Math.max(this.clicked.cy -
this.e.clientY +
this.clicked.h, this.minHeight);
if (currentHeight > this.minHeight) {
this.element.nativeElement.style.height = currentHeight + 'px';
this.element.nativeElement.style.top = this.e.clientY + 'px';
}
}
return;
}
}
onUp(ev) {
this.calc(ev);
this.clicked = null;
}
}
HTML snippet on which directive has been applied
<div class="box" *ngFor="let box of dropzone1" appDroppable (dragStart)="currentBox = box" appMovable>
{{ box.dis }}
<div class="side side-h" id="side-top" (dragStart)=(e) (dragMove)=(e) (dragEnd)=(e) appResizable></div>
<div class="side side-v" id="side-right" (click)="clcikme(e)" ></div>
<div class="side side-h" id="side-bottom" (click)="clcikme(e)"></div>
<div class="side side-v" id="side-left" (click)="clcikme(e)"></div>
</div>
In the codepen example for b
this.b = this.element.nativeElement.getBoundingClientRect();
the whole element has been taken which I'll also have to do, in my case I have the border on which the directive is there
I am attaching a working stackblitz the resizable directive is present in draggable folder and used in hello component
In the stackblitz console logging of pointerdown, pointermove can also be seen.
https://stackblitz.com/edit/angular-pcpev1?file=src/app/hello.component.html
Error in console animate of undefined
Please refer to the codepen example from the comments.
Update
https://stackblitz.com/edit/angular-pcpev1?file=src%2Fapp%2Fhello.component.html

Sorry I can't fix your code because it's a mess, you just do this completely wrong, you just did two approaches I suggest in one code. Also you're leaking resize internals outside of directive, the divs need to be hidden, outside you only should use resize attribute and everything should be created inside directive.
Here, this is started for one top side:
#Directive({
selector: '[resize]'
})
class Resizable implements OnInit, OnDestroy {
private nodes: HtmlElement[] = [];
private data: {x: number, y: number, rect: ClientRect, direction: string};
constructor(#Inject(ElementRef) private element: ElementRef) {
this.mousemove = this.mousemove.bind(this);
this.mouseup = this.mouseup.bind(this);
}
mousemove(e) {
if (this.data) {
switch(this.data.direction) {
case 'top':
var offset = this.data.y - e.clientY;
var height = this.data.rect.height;
var top = this.data.rect.top;
var style = this.element.nativeElement.style;
style.height = height + offset + 'px';
style.top = top - offset + 'px';
break;
}
}
}
ngOnInit() {
var node = document.createElement('div');
node.classList.add('border-top', 'border');
this.element.nativeElement.appendChild(node);
this.nodes.push(node);
window.addEventListener('mousemove', this.mousemove);
window.addEventListener('mouseup', this.mouseup);
}
#HostListener('mousedown', ['$event'])
mousedown(e) {
if (e.target.classList.contains('border')) {
var rect = this.element.nativeElement.getBoundingClientRect();
this.data = {
x: e.clientX,
y: e.clientY,
rect,
direction: e.target.className.match(/border-([^ ]+)/)[1]
};
e.preventDefault();
} else {
delete this.data;
}
}
mouseup(e) {
delete this.data;
}
ngOnDestroy() {
this.nodes.forEach(n => n.remove());
window.removeEventListener('mousemove', this.mousemove);
window.removeEventListener('mouseup', this.mouseup);
}
}
here is CodePen demo

Related

Freeze scrollbar

I create a game using javascript. The code is placed at the bottom of the page. Visualize it as if the game is below a footer. The game starts when the user selects the start game button. The mechanics of the game are controlled by the arrow key. Arrow keys are used to move up, right, and left down. The problem is when I press the up or down key, the page scrolls too. How to stop this? I want the page not to scroll when the game is active. I am attaching the code of the game I create. It is a snake game.There's CSS too, but I'm not attaching it as I don't think its relevant
<div id="app" class="app">
<div class="start-screen">
<h2>šŸ¦Š </h2>
<div class="options">
<h3>Choose Difficulty</h3>
<p class="end-score"></p>
<button data-difficulty="100" class="active">Easy</button>
<button data-difficulty="75">Medium</button>
<button data-difficulty="50">Hard</button>
</div>
<button class="play-btn">Play</button>
</div>
<canvas id="board"></canvas>
<div class="score">0</div>
</div>
<script>
class SnakeGame {
constructor() {
this.$app = document.querySelector('#app');
this.$canvas = this.$app.querySelector('canvas');
this.ctx = this.$canvas.getContext('2d');
this.$startScreen = this.$app.querySelector('.start-screen');
this.$score = this.$app.querySelector('.score');
this.settings = {
canvas: {
width: 500,
height: 500,
background: 'white',
border: 'black'
},
snake: {
size: 20,
background: '#73854A',
border: '#000'
}
};
this.game = {
// "direction" (set in setUpGame())
// "nextDirection" (set in setUpGame())
// "score" (set in setUpGame())
speed: 100,
keyCodes: {
38: 'up',
40: 'down',
39: 'right',
37: 'left'
}
}
this.soundEffects = {
score: new Audio('./sounds/score.mp3'),
gameOver: new Audio('./sounds/game-over.mp3')
};
this.setUpGame();
this.init();
}
init() {
// Choose difficulty
// Rather than using "this.$startScreen.querySelectorAll('button')" and looping over the node list
// and attaching seperate event listeners on each item, it's more efficient to just listen in on the container and run a check at runtime
this.$startScreen.querySelector('.options').addEventListener('click', event => {
this.chooseDifficulty(event.target.dataset.difficulty);
});
// Play
this.$startScreen.querySelector('.play-btn').addEventListener('click', () => {
this.startGame();
});
}
chooseDifficulty(difficulty) {
if(difficulty) {
this.game.speed = difficulty;
this.$startScreen.querySelectorAll('.options button').forEach(btn => btn.classList.remove('active'));
event.target.classList.add('active');
}
}
setUpGame() {
// The snake starts off with 5 pieces
// Each piece is 30x30 pixels
// Each following piece must be n times as far from the first piece
const x = 300;
const y = 300;
this.snake = [
{ x: x, y: y },
{ x: x - this.settings.snake.size, y: y },
{ x: x - (this.settings.snake.size * 2), y: y },
{ x: x - (this.settings.snake.size * 3), y: y },
{ x: x - (this.settings.snake.size * 4), y: y }
];
this.food = {
active: false,
background: '#EC5E0B',
border: '#73AA24',
coordinates: {
x: 0,
y: 0
}
};
this.game.score = 0;
this.game.direction = 'right';
this.game.nextDirection = 'right';
}
startGame() {
// Stop the game over sound effect if a new game was restarted quickly before it could end
this.soundEffects.gameOver.pause();
this.soundEffects.gameOver.currentTime = 0;
// Reset a few things from the prior game
this.$app.classList.add('game-in-progress');
this.$app.classList.remove('game-over');
this.$score.innerText = 0;
this.generateSnake();
this.startGameInterval = setInterval(() => {
if(!this.detectCollision()) {
this.generateSnake();
} else {
this.endGame();
}
}, this.game.speed);
// Change direction
document.addEventListener('keydown', event => {
this.changeDirection(event.keyCode);
});
}
changeDirection(keyCode) {
const validKeyPress = Object.keys(this.game.keyCodes).includes(keyCode.toString()); // Only allow (up|down|left|right)
if(validKeyPress && this.validateDirectionChange(this.game.keyCodes[keyCode], this.game.direction)) {
this.game.nextDirection = this.game.keyCodes[keyCode];
}
}
// When already moving in one direction snake shouldn't be allowed to move in the opposite direction
validateDirectionChange(keyPress, currentDirection) {
return (keyPress === 'left' && currentDirection !== 'right') ||
(keyPress === 'right' && currentDirection !== 'left') ||
(keyPress === 'up' && currentDirection !== 'down') ||
(keyPress === 'down' && currentDirection !== 'up');
}
resetCanvas() {
// Full screen size
this.$canvas.width = this.settings.canvas.width;
this.$canvas.height = this.settings.canvas.height;
this.$canvas.style.border = `3px solid ${this.settings.canvas.border}`;
// Background
this.ctx.fillStyle = this.settings.canvas.background;
this.ctx.fillRect(0, 0, this.$canvas.width, this.$canvas.height);
}
generateSnake() {
let coordinate;
switch(this.game.direction) {
case 'right':
coordinate = {
x: this.snake[0].x + this.settings.snake.size,
y: this.snake[0].y
};
break;
case 'up':
coordinate = {
x: this.snake[0].x,
y: this.snake[0].y - this.settings.snake.size
};
break;
case 'left':
coordinate = {
x: this.snake[0].x - this.settings.snake.size,
y: this.snake[0].y
};
break;
case 'down':
coordinate = {
x: this.snake[0].x,
y: this.snake[0].y + this.settings.snake.size
};
}
// The snake moves by adding a piece to the beginning "this.snake.unshift(coordinate)" and removing the last piece "this.snake.pop()"
// Except when it eats the food in which case there is no need to remove a piece and the added piece will make it grow
this.snake.unshift(coordinate);
this.resetCanvas();
const ateFood = this.snake[0].x === this.food.coordinates.x && this.snake[0].y === this.food.coordinates.y;
if(ateFood) {
this.food.active = false;
this.game.score += 10;
this.$score.innerText = this.game.score;
this.soundEffects.score.play();
} else {
this.snake.pop();
}
this.generateFood();
this.drawSnake();
}
drawSnake() {
const size = this.settings.snake.size;
this.ctx.fillStyle = this.settings.snake.background;
this.ctx.strokestyle = this.settings.snake.border;
// Draw each piece
this.snake.forEach(coordinate => {
this.ctx.fillRect(coordinate.x, coordinate.y, size, size);
this.ctx.strokeRect(coordinate.x, coordinate.y, size, size);
});
this.game.direction = this.game.nextDirection;
}
generateFood() {
// If there is uneaten food on the canvas there's no need to regenerate it
if(this.food.active) {
this.drawFood(this.food.coordinates.x, this.food.coordinates.y);
return;
}
const gridSize = this.settings.snake.size;
const xMax = this.settings.canvas.width - gridSize;
const yMax = this.settings.canvas.height - gridSize;
const x = Math.round((Math.random() * xMax) / gridSize) * gridSize;
const y = Math.round((Math.random() * yMax) / gridSize) * gridSize;
// Make sure the generated coordinates do not conflict with the snake's present location
// If so recall this method recursively to try again
this.snake.forEach(coordinate => {
const foodSnakeConflict = coordinate.x == x && coordinate.y == y;
if(foodSnakeConflict) {
this.generateFood();
} else {
this.drawFood(x, y);
}
});
}
drawFood(x, y) {
const size = this.settings.snake.size;
this.ctx.fillStyle = this.food.background;
this.ctx.strokestyle = this.food.border;
this.ctx.fillRect(x, y, size, size);
this.ctx.strokeRect(x, y, size, size);
this.food.active = true;
this.food.coordinates.x = x;
this.food.coordinates.y = y;
}
detectCollision() {
// Self collison
// It's impossible for the first 3 pieces of the snake to self collide so the loop starts at 4
for(let i = 4; i < this.snake.length; i++) {
const selfCollison = this.snake[i].x === this.snake[0].x && this.snake[i].y === this.snake[0].y;
if(selfCollison) {
return true;
}
}
// Wall collison
const leftCollison = this.snake[0].x < 0;
const topCollison = this.snake[0].y < 0;
const rightCollison = this.snake[0].x > this.$canvas.width - this.settings.snake.size;
const bottomCollison = this.snake[0].y > this.$canvas.height - this.settings.snake.size;
return leftCollison || topCollison || rightCollison || bottomCollison;
}
endGame() {
this.soundEffects.gameOver.play();
clearInterval(this.startGameInterval);
this.$app.classList.remove('game-in-progress');
this.$app.classList.add('game-over');
this.$startScreen.querySelector('.options h3').innerText = 'Game Over';
this.$startScreen.querySelector('.options .end-score').innerText = `Score: ${this.game.score}`;
this.setUpGame();
}
}
const snakeGame = new SnakeGame();
</script>
Stop the page from moving up and down when the game is active
You just need to prevent the default behaviour of these keys:
// Change direction
document.addEventListener('keydown', event => {
event.preventDefault(); // add this line
this.changeDirection(event.keyCode);
});
Note that this isn't a very good idea to do it that way, as it will prevent the default behaviour of all keypresses anywhere on your page. Most notably, F5 will never refresh the browser, and if you have other elements like buttons, links, etc, the standard keypresses to activate those will stop working (turning these off is a particular problem if you want your site to be accessible to those with disabilities).
You'd be better off checking the keyCode first and only preventing default if it corresponds to one of the arrow keys - which isn't so easy to do with your code as it stands but I'd encourage you to rewrite it that way.
Even doing that presents a problem to those who are not able to use a mouse, as (depending on the position of your game interface on the screen and its size) they may still need to scroll down and will be prevented from doing this by this preventDefault behaviour. But well that's what you asked for, and I've given you the solution - but with this important caveat.

How can I use composition with methods in ES6 Classes?

I am struggling to implement composition in ES6 classes! I am trying to understand a lot of things at once and have maybe made a stupid error.
I would like to avoid inheritance using extend and super for now, and have found this nice example of composition that seems to show what I am after:
class EmployeeTaxData {
constructor(ssn, salary) {
this.ssn = ssn;
this.salary = salary;
}
// ...
}
class Employee {
constructor(name, email) {
this.name = name;
this.email = email;
}
setTaxData(ssn, salary) {
this.taxData = new EmployeeTaxData(ssn, salary);
}
// ...
}
In regard to the code below, I would like to use the most simple and eloquent way to make the spin() method available for the objects created by the Hero class so it is using a shared prototype. I would like to share this method with other objects that will need it too.
Unfortunately I can't make my code work as the this.angle is not referring to to the Hero class that it needs to, but the Spinner class?
class Spinner {
constructor(direction){
this.direction = direction;
}
spin(direction) {
switch (direction) {
case 'left':
this.angle -= 1;
break;
case 'right':
this.angle += 1;
break;
// no default
}
}
}
class Hero {
constructor(xPosition, yPosition) {
this.description = 'hero';
this.width = 25;
this.height = 50;
this.xPosition = xPosition;
this.yPosition = yPosition;
this.angle = 0;
this.color = 'red';
this.spin = new Spinner();
}
spin() {
this.spin.spin();
}
}
const heroClass = new Hero(100, 200);
console.log(heroClass.angle); // result is 0
heroClass.spin.spin('left');
console.log(heroClass.angle); // result is STILL 0, it didn't work
...the this.angle is not referring to to the Hero class that it needs to, but the Spinner class?
As it should. When you're inside the spinner class, then this refers to a spinner object, which also means this.angle inside the spinner class refers to an angle property of a spinner object.
You'll probably want spinner to return a new angle value, then the hero object that uses spinner should save the returned new angle value.
class Spinner {
constructor(direction){
this.direction = direction;
}
spin(direction, angle) {
switch (direction) {
case 'left':
angle -= 1;
break;
case 'right':
angle += 1;
break;
// no default
}
return angle;
}
}
class Hero {
constructor(xPosition, yPosition) {
this.description = 'hero';
this.width = 25;
this.height = 50;
this.xPosition = xPosition;
this.yPosition = yPosition;
this.angle = 0;
this.color = 'red';
this.spinner = new Spinner();
}
spin(direction) {
this.angle = this.spinner.spin(direction, this.angle);
}
}
const heroClass = new Hero(100, 200);
console.log(heroClass.angle); // result is 0
heroClass.spin('left');
console.log(heroClass.angle); // result is -1
I had to make a few other small changes for this to work. For example, you had a data property named "spin" this.spin = new Spinner as well as a method named spin spin() {. They were overriding one another.

Vue mousemove only after mousedown

How can I trigger a mousemove only if the element is clicked first?
I'm trying to utilize this for an audio player timeline.
.player__time--bar(#mousedown="setNewCurrentPosition($event)")
.slider(role="slider" aria-valuemin="0" :aria-valuenow="currentPosition" :aria-valuemax="trackTotalDuration" aria-orientation="horizontal")
.player__time--bar-current-position(:style="{width: (100 / (trackTotalDuration / currentPosition)) + '%'}")
The method:
setNewCurrentPosition(e) {
let tag = e.target
// if the click is not on 'slider', grab div with class 'slider'
if (e.target.className === 'player__time--bar') tag = e.target.firstElementChild
else if (e.target.className === 'player__time--bar-current-position') tag = e.target.parentElement
const pos = tag.getBoundingClientRect()
const seekPos = (e.clientX - pos.left) / pos.width
this.currentPosition = parseInt(this.trackTotalDuration * seekPos)
// updates the time in the html
this.$refs.player.currentTime = this.currentPosition
},
You will want to have a mousedown listener on your element that sets a variable to indicate dragging started. Put a listener on the window to catch mouseup anywhere and unset the variable.
You can put mousemove on the element if you are only interested in dragging that happens inside the element. Otherwise you can put the mousemove listener on window so you catch it everywhere.
new Vue({
el: '#app',
data: {
dragging: false,
x: 'no',
y: 'no'
},
methods: {
startDrag() {
this.dragging = true;
this.x = this.y = 0;
},
stopDrag() {
this.dragging = false;
this.x = this.y = 'no';
},
doDrag(event) {
if (this.dragging) {
this.x = event.clientX;
this.y = event.clientY;
}
}
},
mounted() {
window.addEventListener('mouseup', this.stopDrag);
}
});
.dragstartzone {
background-color: red;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<div class="dragstartzone" #mousedown="startDrag" #mousemove="doDrag">Start dragging here</div>
<div>X: {{x}}, Y: {{y}}</div>
</div>
I ended up using the code provided by Roy J, refactoring it a bit to fit my need. Here it is
Template:
.player__time--bar(#mousedown="startDrag($event)" #mouseup="stopDrag($event)" #mousemove="doDrag($event)")
.slider(role="slider" aria-valuemin="0" :aria-valuenow="currentPosition" :aria-valuemax="trackTotalDuration" aria-orientation="horizontal")
.player__time--bar-current-position(:style="{width: (100 / (trackTotalDuration / currentPosition)) + '%'}")
Data:
data: () => ({
currentPosition: 0,
trackTotalDuration: 0,
dragging: false
}),
Methods:
startDrag() {
this.dragging = true
},
stopDrag(event) {
this.dragging = false
this.setNewCurrentPosition(event)
},
doDrag(event) {
if (this.dragging) this.setNewCurrentPosition(event)
},
setNewCurrentPosition(e) {
let tag = e.target
// if the click is not on 'slider', grab div with class 'slider'
if (e.target.className === 'player__time--bar') tag = e.target.firstElementChild
else if (e.target.className === 'player__time--bar-current-position') tag = e.target.parentElement
const pos = tag.getBoundingClientRect()
const seekPos = (e.clientX - pos.left) / pos.width
this.currentPosition = parseInt(this.trackTotalDuration * seekPos)
// updates the time in the html
this.$refs.player.currentTime = this.currentPosition
},

rotating SVG rect around its center using vanilla JavaScript

This is not a duplicate of the other question.
I found this talking about rotation about the center using XML, tried to implement the same using vanilla JavaScript like rotate(45, 60, 60) but did not work with me.
The approach worked with me is the one in the snippet below, but found the rect not rotating exactly around its center, and it is moving little bit, the rect should start rotating upon the first click, and should stop at the second click, which is going fine with me.
Any idea, why the item is moving, and how can I fix it.
var NS="http://www.w3.org/2000/svg";
var SVG=function(el){
return document.createElementNS(NS,el);
}
var svg = SVG("svg");
svg.width='100%';
svg.height='100%';
document.body.appendChild(svg);
class myRect {
constructor(x,y,h,w,fill) {
this.SVGObj= SVG('rect'); // document.createElementNS(NS,"rect");
self = this.SVGObj;
self.x.baseVal.value=x;
self.y.baseVal.value=y;
self.width.baseVal.value=w;
self.height.baseVal.value=h;
self.style.fill=fill;
self.onclick="click(evt)";
self.addEventListener("click",this,false);
}
}
Object.defineProperty(myRect.prototype, "node", {
get: function(){ return this.SVGObj;}
});
Object.defineProperty(myRect.prototype, "CenterPoint", {
get: function(){
var self = this.SVGObj;
self.bbox = self.getBoundingClientRect(); // returned only after the item is drawn
self.Pc = {
x: self.bbox.left + self.bbox.width/2,
y: self.bbox.top + self.bbox.height/2
};
return self.Pc;
}
});
myRect.prototype.handleEvent= function(evt){
self = evt.target; // this returns the `rect` element
this.cntr = this.CenterPoint; // backup the origional center point Pc
this.r =5;
switch (evt.type){
case "click":
if (typeof self.moving == 'undefined' || self.moving == false) self.moving = true;
else self.moving = false;
if(self.moving == true){
self.move = setInterval(()=>this.animate(),100);
}
else{
clearInterval(self.move);
}
break;
default:
break;
}
}
myRect.prototype.step = function(x,y) {
return svg.createSVGTransformFromMatrix(svg.createSVGMatrix().translate(x,y));
}
myRect.prototype.rotate = function(r) {
return svg.createSVGTransformFromMatrix(svg.createSVGMatrix().rotate(r));
}
myRect.prototype.animate = function() {
self = this.SVGObj;
self.transform.baseVal.appendItem(this.step(this.cntr.x,this.cntr.y));
self.transform.baseVal.appendItem(this.rotate(this.r));
self.transform.baseVal.appendItem(this.step(-this.cntr.x,-this.cntr.y));
};
for (var i = 0; i < 10; i++) {
var x = Math.random() * 100,
y = Math.random() * 300;
var r= new myRect(x,y,10,10,'#'+Math.round(0xffffff * Math.random()).toString(16));
svg.appendChild(r.node);
}
UPDATE
I found the issue to be calculating the center point of the rect using the self.getBoundingClientRect() there is always 4px extra in each side, which means 8px extra in the width and 8px extra in the height, as well as both x and y are shifted by 4 px, I found this talking about the same, but neither setting self.setAttribute("display", "block"); or self.style.display = "block"; worked with me.
So, now I've one of 2 options, either:
Find a solution of the extra 4px in each side (i.e. 4px shifting of both x and y, and total 8px extra in both width and height),
or calculating the mid-point using:
self.Pc = {
x: self.x.baseVal.value + self.width.baseVal.value/2,
y: self.y.baseVal.value + self.height.baseVal.value/2
};
The second option (the other way of calculating the mid-point worked fine with me, as it is rect but if other shape is used, it is not the same way, I'll look for universal way to find the mid-point whatever the object is, i.e. looking for the first option, which is solving the self.getBoundingClientRect() issue.
Here we goā€¦
FIDDLE
Some code for documentation here:
let SVG = ((root) => {
let ns = root.getAttribute('xmlns');
return {
e (tag) {
return document.createElementNS(ns, tag);
},
add (e) {
return root.appendChild(e)
},
matrix () {
return root.createSVGMatrix();
},
transform () {
return root.createSVGTransformFromMatrix(this.matrix());
}
}
})(document.querySelector('svg.stage'));
class Rectangle {
constructor (x,y,w,h) {
this.node = SVG.add(SVG.e('rect'));
this.node.x.baseVal.value = x;
this.node.y.baseVal.value = y;
this.node.width.baseVal.value = w;
this.node.height.baseVal.value = h;
this.node.transform.baseVal.initialize(SVG.transform());
}
rotate (gamma, x, y) {
let t = this.node.transform.baseVal.getItem(0),
m1 = SVG.matrix().translate(-x, -y),
m2 = SVG.matrix().rotate(gamma),
m3 = SVG.matrix().translate(x, y),
mtr = t.matrix.multiply(m3).multiply(m2).multiply(m1);
this.node.transform.baseVal.getItem(0).setMatrix(mtr);
}
}
Thanks #Philipp,
Solving catching the SVG center can be done, by either of the following ways:
Using .getBoundingClientRect() and adjusting the dimentions considering 4px are extra in each side, so the resulted numbers to be adjusted as:
BoxC = self.getBoundingClientRect();
Pc = {
x: (BoxC.left - 4) + (BoxC.width - 8)/2,
y: (BoxC.top - 4) + (BoxC.height - 8)/2
};
or by:
Catching the .(x/y).baseVal.value as:
Pc = {
x: self.x.baseVal.value + self.width.baseVal.value/2,
y: self.y.baseVal.value + self.height.baseVal.value/2
};
Below a full running code:
let ns="http://www.w3.org/2000/svg";
var root = document.createElementNS(ns, "svg");
root.style.width='100%';
root.style.height='100%';
root.style.backgroundColor = 'green';
document.body.appendChild(root);
//let SVG = function() {}; // let SVG = new Object(); //let SVG = {};
class SVG {};
SVG.matrix = (()=> { return root.createSVGMatrix(); });
SVG.transform = (()=> { return root.createSVGTransformFromMatrix(SVG.matrix()); });
SVG.translate = ((x,y)=> { return SVG.matrix().translate(x,y) });
SVG.rotate = ((r)=> { return SVG.matrix().rotate(r); });
class Rectangle {
constructor (x,y,w,h,fill) {
this.node = document.createElementNS(ns, 'rect');
self = this.node;
self.x.baseVal.value = x;
self.y.baseVal.value = y;
self.width.baseVal.value = w;
self.height.baseVal.value = h;
self.style.fill=fill;
self.transform.baseVal.initialize(SVG.transform()); // to generate transform list
this.transform = self.transform.baseVal.getItem(0), // to be able to read the matrix
this.node.addEventListener("click",this,false);
}
}
Object.defineProperty(Rectangle.prototype, "draw", {
get: function(){ return this.node;}
});
Object.defineProperty(Rectangle.prototype, "CenterPoint", {
get: function(){
var self = this.node;
self.bbox = self.getBoundingClientRect(); // There is 4px shift in each side
self.bboxC = {
x: (self.bbox.left - 4) + (self.bbox.width - 8)/2,
y: (self.bbox.top - 4) + (self.bbox.height - 8)/2
};
// another option is:
self.Pc = {
x: self.x.baseVal.value + self.width.baseVal.value/2,
y: self.y.baseVal.value + self.height.baseVal.value/2
};
return self.bboxC;
// return self.Pc; // will give same output of bboxC
}
});
Rectangle.prototype.animate = function () {
let move01 = SVG.translate(this.CenterPoint.x,this.CenterPoint.y),
move02 = SVG.rotate(10),
move03 = SVG.translate(-this.CenterPoint.x,-this.CenterPoint.y);
movement = this.transform.matrix.multiply(move01).multiply(move02).multiply(move03);
this.transform.setMatrix(movement);
}
Rectangle.prototype.handleEvent= function(evt){
self = evt.target; // this returns the `rect` element
switch (evt.type){
case "click":
if (typeof self.moving == 'undefined' || self.moving == false) self.moving = true;
else self.moving = false;
if(self.moving == true){
self.move = setInterval(()=>this.animate(),100);
}
else{
clearInterval(self.move);
}
break;
default:
break;
}
}
for (var i = 0; i < 10; i++) {
var x = Math.random() * 100,
y = Math.random() * 300;
var r= new Rectangle(x,y,10,10,'#'+Math.round(0xffffff * Math.random()).toString(16));
root.appendChild(r.draw);
}

rotate on mouse hover

I have this function but there are two issues I can't solve, first one is that the mouse action is set on all the screen and I want it to be when hover over the dive "ehab" only, not when I move mouse over screen,
the other issue is that when I have more than one div , the function works only on the first one ...
kindly advise me
/*
By : Ofelquis
Twitter: #felquis
Blog : tutsmais.com.br
Simples implementaĆ§Ć£o ;)
*/
!(function ($doc, $win) {
var screenWidth = $win.screen.width / 2,
screenHeight = $win.screen.height / 2,
$ehab = $doc.querySelectorAll('#ehab')[0],
validPropertyPrefix = '',
otherProperty = 'perspective(600px)';
if(typeof $ehab.style.webkitTransform == 'string') {
validPropertyPrefix = 'webkitTransform';
} else {
if (typeof $ehab.style.MozTransform == 'string') {
validPropertyPrefix = 'MozTransform';
}
}
$doc.addEventListener('mousemove', function (e) {
// vars
var centroX = e.clientX - screenWidth,
centroY = screenHeight - (e.clientY + 13),
degX = centroX * 0.1,
degY = centroY * 0.1
// Seta o rotate do elemento
$ehab.style[validPropertyPrefix] = otherProperty + 'rotateY('+ degX +'deg) rotateX('+ degY +'deg)';
});
})(document, window);
The first problem, (I want it to be when hover the div "#ehab"), you need the attach the mousemove event to your div:
$ehab.addEventListener('mousemove', function (e) {
//You code here.
});
The second problem, (when I have more than one div , the function works only on the first one), you can't have duplicated IDs on your DOM tree, change the selector to a class, for example, .ehab then you have to loop through the matched elements, please try this code:
/*
By : Ofelquis
Twitter: #felquis
Blog : tutsmais.com.br
Simples implementaĆ§Ć£o ;)
*/
!(function($doc, $win) {
var $ehabDIVs = $doc.querySelectorAll('.ehab'),
otherProperty = 'perspective(600px)';
for (var i = 0; i < $ehabDIVs.length; ++i) {
var $ehab = $ehabDIVs[i];
$ehab.addEventListener('mousemove', function(e) {
// vars
var centroX = (e.pageX - this.offsetLeft) - this.offsetWidth/2,
centroY = this.offsetHeight/2 - (e.pageY-this.offsetTop),
degX = centroX * 0.1,
degY = centroY * 0.1
if(this._leave) clearInterval(this._leave);
// Seta o rotate do elemento
this.style.transform = otherProperty + 'rotateY(' + degX + 'deg) rotateX(' + degY + 'deg)';
});
$ehab.addEventListener('mouseleave', function(e) {
var self = this;
this._leave = setTimeout(function() {
self.style.transform = 'rotateY(0deg) rotateX(0deg)';
}, 250);
});
}
})(document, window);
.ehab {
width:300px;
height:300px;
background-color:red;
margin:15px;
float:left;
transition: transform 0.15s ease;
}
<div class="ehab">First Div</div><div class="ehab">Second Div</div>
Good Luck Ismaiel.

Categories

Resources