rotating SVG rect around its center using vanilla JavaScript - 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);
}

Related

Phaser game getting slow [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Fist time i am using phaser.io, i am repeating background and also loading other thing in update function but after few second later my game is slowing time . it look like background is not moving more. Please have a look of my code and help me in for sort out this problem. Or please give any idea to change background repeatedly without changing other thing.
I have some code indentation problem sorry for that but please try to manage and help me.
Game.js
var scoreTxt, score, speed, scoreTextValue, ques_label, ques_label_pizza, scoreTextKey, timerTextValue, timerTextKey, textStyle_Key, textStyle_Value, anscloud, astroid1, astroid2, astroid3, astroid4;
/*var gameType;*/ //Pizza or Noun
var bullets, quesTextValue, ansTextValue, sprite;
var fireRate = 100;
var nextFire = 0;
var xAxis = [];
var yAxis = [];
var tempQues = [];
var tempAns = [];
var result = [];
var answear = [];
var ques = [];
var astroidContains = [];
var astroidContainsText = []; //['right', 'wrong', 'wrong', 'wrong']
var astroid, spaceShip, quesbar, diamond, randomAnsPosition;
var s1Copy;
var cloudContains = []; //['noun', 'pronoun', 'pronoun']
var QbarContainsQue = [];
var ans,rightans;
var isAnswerCorrect = false;
var allowClick = false;
var spaceShipXAxis = 40, loader1Width = 85, loader2Width = 70;
var bar, loader1, loader2, timer, timerSprite, timerSpriteCount = 0;
var timerCounter = 45; //timer counter will be of 45 seconds.
//var timerCounter_ = 100; //timer counter will be of 45 seconds.
var questCounter = 0; //question counter no. of question played.
var maxQuest = 10;//max questions will be displayed is 10.
var diamondTextColor = "#8D4FA8";
var defTextColor = "#5BEFFE";
var ansTextColor = "#9E13DA";
var errTextColor = '#FF0000';
var corrTextColor = '#228B22';
var corr_ans_fst;
var corr_ans_sec;
var fun_bckg, randQues;
var wrong_ans;
var barre1_x = 150;
var barre1_y = 115;
var healthValue = 100;
var x_loader = 180;
var check =0;
var setAns = [];
var setOne = [['12+16=','28'], ['15+11=','26'], ['16+22=','38'], ['13+14=','27'], ['15+24=','39'], ['14+12=','26'], ['10+17=','27'], ['11+11=','22'],
['13+15=','28'], ['12+21=','33'], ['24+13=','37'], ['33+21=','54'], ['40+18=','58'], ['34+31=','65'], ['25+42=','67'], ['22+15=','37'],
['24+12=','36'], ['20+15=','35'], ['25+14=','39'], ['21+21=','42'], ['41+25=','66'], ['53+24=','77'], ['35+31=','66'], ['62+37=','99'],
['54+35=','89']];
var setTwo = [['15+18=','33'], ['17+17=','34'], ['13+19=','32'], ['18+14=','32'], ['15+27=','42'], ['18+17=','35'], ['27+29=','56'], ['23+28=','51'],
['36+37=','73'], ['45+25=','70'], ['46+45=','91'], ['38+57=','95'], ['49+43=','92'], ['37+53=','90'], ['48+33=','81']];
var Game = {
preload : function() {
// Load the needed image for this(play) game screen.
//load the menu screen
this.load.image('menu', './assets/images/menu.png');
// Here we load all the needed resources for the level.
// background image screen
this.load.image('playgame', './assets/images/back.png');
// globe image screen
this.load.image('playgame', './assets/images/back.png');
// win image screen
//this.load.image('win', './assets/images/win.png');
// spaceship image screen
this.load.image('spaceship', './assets/images/spaceship.png');
// Question bar image screen
this.load.image('quesbar', './assets/images/quesbar.png');
// Diamond image screen
this.load.image('diamond', './assets/images/diamond.png');
// Astroid image screen
this.load.image('astroid1', 'assets/images/asteroid1.png');
this.load.image('astroid2', 'assets/images/asteroid2.png');
this.load.image('astroid3', 'assets/images/asteroid3.png');
this.load.image('astroid4', 'assets/images/asteroid4.png');
// Loader image screen
this.load.image('loaderbck', 'assets/images/loaderbck.png');
this.load.image('loader1', 'assets/images/loader1.png');
this.load.image('loader2', 'assets/images/loader2.png');
//Load the bullet
this.load.image('bullet', 'assets/images/bullet.png');
},
create : function() {
// By setting up global variables in the create function, we initialise them on game start.
// We need them to be globally available so that the update function can alter them.
textStyle_Value = { font: "bold 20px Segoe UI", fill: defTextColor, align: "center" };
textStyleAns = { font: "bold 22px 'Comic Sans MS', 'Comic Sans'", fill: ansTextColor, wordWrap: true, wordWrapWidth: 10, align: "center"};
textStyleQues = { font: "bold 20px 'Comic Sans MS', 'Comic Sans'", fill: defTextColor, wordWrap: true, wordWrapWidth: 10, align: "center"};
sprite = game.add.sprite(310, 485, 'spaceship');
sprite.anchor.set(0.5);
// Loading backround image
this.playBackground();
this.playBackground1();
// Additional Sprites, like cloud
this.addSprites();
// Loading spaceship image
//this.spaceship();
// Loading questionbar image
this.questionbar();
// Call fun. for ques
this.comeQus();
// csll fun. for place astroid
// this.astroid();
// call fun. for Ans
this.generateQues();
this.generateAns();
// Loading Diamond image
this.diamond();
// Start timer
this.startTimer();
// Set timer.
this.setTimer();
this.initLoader();
},
update: function() {
// The update function is called constantly at a high rate (somewhere around 60fps),
// updating the game field every time - also destroying previous objects and creating new.
// Our bullet group
//bullets.destroy();
sprite.destroy();
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(200, 'bullet', 100, false);
bullets.setAll('anchor.x',0);
bullets.setAll('anchor.y', 0.9);
bullets.setAll('outOfBoundsKill', true);
bullets.setAll('checkWorldBounds', true);
//Repeating background..
if(playgame != null && playgame.body.y > 600) {
playgame.destroy();
this.playBackground();
}
if(playgame1.body.y > 0) {
playgame1.destroy();
this.playBackground1();
this.initLoader();
}
if(astroid1 != undefined) astroid1.destroy();
if(astroid2 != undefined) astroid2.destroy();
if(astroid3 != undefined) astroid3.destroy();
if(astroid4 != undefined) astroid4.destroy();
this.addSprites();
//timerTextValue.text = "00:" + timerCounter;
this.initLoader();
//destroing old diamond obj and creating new while change background
//diamond.destroy();
this.diamond();
//destroing old questionbar obj and creating new while change background
quesbar.destroy();
this.questionbar();
//Call comeQus, comeAns for show ques and ans at every background change
// quesTextValue.destroy();
if(quesTextValue != undefined) quesTextValue.destroy();
this.comeQus();
//ansTextValue.destroy();
if(ansTextValue != undefined) ansTextValue.destroy();
this.comeAns();
if (game.input.activePointer.isDown) {
this.fire();
}
allowClick = true;
},
playBackground: function() {
// console.log("playBackground called");
playgame = this.add.sprite(0, 0, 'playgame', 5);
playgame.scale.set(1);
playgame.smoothed = false;
anim_playgame = playgame.animations.add('walk');
anim_playgame.play(10, true);
this.physics.enable(playgame, Phaser.Physics.ARCADE);
playgame.body.velocity.y = 50;
},
playBackground1: function() {
//console.log("playBackground1 called");
//Second background..
playgame1 = this.add.sprite(0, -600, 'playgame', 5);
playgame1.scale.set(1);
playgame1.smoothed = false;
anim_playgame1 = playgame1.animations.add('walk');
anim_playgame1.play(10, true);
this.physics.enable(playgame1, Phaser.Physics.ARCADE);
playgame1.body.velocity.y = 50;
},
questionbar: function() {
quesbar = game.add.image(10, 530, 'quesbar');
},
diamond: function() {
diamond = game.add.image(680, 20, 'diamond');
},
addSprites: function() {
// loading answer cloud
astroid1 = this.add.button(30, 90, 'astroid1', this.astroidClicked, this);
astroid2 = this.add.button(220, 30, 'astroid2', this.astroidClicked, this);
astroid3 = this.add.button(400, 40, 'astroid3', this.astroidClicked, this);
astroid4 = this.add.button(600, 90, 'astroid4', this.astroidClicked, this);
},
inCorrectAnswerHit: function(index) {
allowClick = false;
isAnswerCorrect = false;
//this.playFx('wrong_ans');
for(i=0; i<=3; i++) {
if(cloudContains[i] == "right") {
//cloudContainsText[i].fill = corrTextColor;
console.log("right ans hit");
break;
}
}
},
checkAnswer: function(index) {
// If clicked Ans is right so astroid will destroy.
if(astroidContainsText[index] == "wrong") {
//Here collization function will call
isAnswerCorrect = true;
}
// If clicked word is noun (correct answer) and obstacle is redbird or blackbird - the dude will slide.
else {
this.inCorrectAnswerHit(index);
}
},
generateQues: function(){
var que;
// Generating random questions from given list of ques - setOne.
s1Copy = setOne.slice();
//var result = [];
for (var i = 0; i < 3; i++) {result.push(s1Copy.splice(~~(Math.random()*s1Copy.length),1)[0]);}
s1Copy.push(...setTwo);
for (var i = 0; i < 7; i++) {result.push(s1Copy.splice(~~(Math.random()*s1Copy.length),1)[0]);}
result.toString();
for(var i = 0; i < result.length ; i++ ) {
que = result[i];
ques.push(que[0]);
ques.toString();
//console.log(ques);
answear.push(que[1]);
}
},
comeQus: function() {
quesTextValue = this.add.text(50,541, ques[0],textStyleQues);
this.generateQues();
//tempNoun = [];
},
generateAns: function() {
//Generate two digitd rendom no. and create an array of ans setAns[]
// Add digitd in array
for(var i = 0; i < 3 ; i++) {
var digit = Math.floor(Math.random() * 90 + 10);
//console.log(digit);
setAns.push(digit);
astroidContains[i] = "wrong";
}
console.log(astroidContains);
//console.log(answear);
setAns.push(answear[0]);
astroidContains[i] = "right";
console.log(astroidContains);
shuffle(setAns);
randomAnsPosition = [0, 1, 2, 3];
shuffle(randomAnsPosition);
},
comeAns: function() {
// x and y axis param for placing Answers text.
xAxis = [ 85, 255, 453, 675];
yAxis = [130, 48, 60, 120];
// console.log(setAns);
// Set Answers from above array of Ans - setAns.
for (var i = 0; i < setAns.length; i++) {
var ans = setAns[i];
//console.log(ans);
ansTextValue = this.add.text(xAxis[randomAnsPosition[i]], yAxis[randomAnsPosition[i]], ans, textStyleAns);
astroidContainsText[i] = ansTextValue;
//console.log(ansTextValue.text);
}
},
// Observing which cloud is clicked and checking answer accordingly.
astroidClicked: function() {
// alert("HEllo called");
if(!allowClick) {
return;
}
if(astroid1.game.input._x > 85 && astroid1.game.input._x < 130) {
console.log("cloud_1_Clicked, Clicked:" + astroidContains[0]);
this.checkAnswer(0);
}
else if(astroid2.game.input._x > 255 && astroid2.game.input._x < 48) {
//console.log("cloud_2_Clicked, Clicked:" + astroidContains[1]);
this.checkAnswer(1);
}
else if(astroid3.game.input._x > 453 && astroid3.game.input._x < 60) {
//console.log("cloud_3_Clicked, Clicked:" + astroidContains[2]);
this.checkAnswer(2);
}
else if(astroid4.game.input._x > 675 && astroid4.game.input._x < 120) {
//console.log("cloud_3_Clicked, Clicked:" + astroidContains[2]);
this.checkAnswer(3);
}
allowClick = false;
},
startTimer: function() {
// Create our Timer
timer = game.time.create(false);
// Set a TimerEvent to occur after 1 seconds
timer.loop(1000, this.updateCounter, this);
// Set a TimerEvent to occur after 1 seconds
// timer.loop(100, this.timerStripeChange, this);
// Start the timer running - this is important!
// It won't start automatically, allowing you to hook it to button events and the like.
timer.start();
},
gameOver: function() {
//Gameover screen
this.state.start('Game_Over', true, false);
},
initLoader: function() {
//*******Loader
check +=1;
var bmd = this.game.add.bitmapData(185, 30);
bmd.ctx.beginPath();
bmd.ctx.rect(0, 0, 185, 36);
bmd.ctx.fillStyle = '#00685e';
bmd.ctx.fill();
var bglife = this.game.add.sprite(100, 38, bmd);
bglife.anchor.set(0.5);
if(check != 0)
bmd = this.game.add.bitmapData(x_loader-4, 26);
else
bmd = this.game.add.bitmapData(x_loader, 26);
bmd.ctx.beginPath();
bmd.ctx.rect(0, 0, 180, 26);
if(x_loader <= 120 && x_loader > 60) {
bmd.ctx.fillStyle = "#FFFF00";
} else if(x_loader <= 60) {
bmd.ctx.fillStyle = "#EA0B1E";
} else {
bmd.ctx.fillStyle = '#00f910';
}
bmd.ctx.fill();
this.widthLife = new Phaser.Rectangle(0, 0, bmd.width, bmd.height);
this.totalLife = bmd.width;
//x_loader = ;
/*console.log(this.totalLife);
console.log(this.widthLife);*/
this.life = this.game.add.sprite(93 - bglife.width/2 + 10, 38, bmd);
this.life.anchor.y = 0.5;
this.life.cropEnabled = true;
this.life.crop(this.widthLife);
// this.game.time.events.loop(1450, this.cropLife, this);
},
updateCounter: function() {
if(timerCounter <= 0) {
this.gameOver();
return;
}
timerCounter--;
if(this.widthLife.width <= 0){
this.widthLife.width = this.totalLife;
}
else{
//this.game.add.tween(this.widthLife).to( { width: (x_loader - 4) }, 200, Phaser.Easing.Linear.None, true);
//console.log(this.widthLife.width);
this.widthLife.width = x_loader - 4;
x_loader = this.widthLife.width;
}
},
fire: function () {
if (game.time.now > nextFire && bullets.countDead() > 0)
{
nextFire = game.time.now + fireRate;
var bullet = bullets.getFirstDead();
bullet.reset(sprite.x - 80, sprite.y - 80);
game.physics.arcade.moveToPointer(bullet, 300);
}
}
}
/**
* Shuffles array in place.
* #param {Array} a items The array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}
As already noted it is a lot of code.
So far what I can see, is a memory leak in the update() function:
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(200, 'bullet', 100, false);
bullets.setAll('anchor.x',0);
bullets.setAll('anchor.y', 0.9);
bullets.setAll('outOfBoundsKill', true);
bullets.setAll('checkWorldBounds', true);
With that you are constantly creating new bullets. Put that in the create() function and try again.

Add multiple ids in a function

I'm trying to make this code work with more than one id and i can't make it work.
I have tried with querySelectorAll, but with not succes.
I also read this article, but none of the options worked for me
Can anyone help me?
This is the code:
<script>
function Scroller(options) {
this.svg = options.el;
//Animation will end when the end is at which point of othe page. .9 is at about 90% down the page/
// .1 is 10% from the top of the page. Default is middle of the page.
this.animationBounds = {};
this.animationBounds.top = options.startPoint || .5;
this.animationBounds.bottom = options.endPoint || .5;
this.animationBounds.containerBounds = this.svg.getBoundingClientRect();
this.start = this.getPagePosition('top');
this.end = this.getPagePosition('bottom');
this.svgLength = this.svg.getTotalLength();
this.svg.style.strokeDasharray = this.svgLength;
this.animateLine();
window.addEventListener('scroll', this.animateLine.bind(this));
}
Scroller.prototype.getPagePosition = function (position) {
//These positions are all relative to the current window. So they top of the page will be negative and thus need to be
//subtracted to get a positive number
var distanceFromPageTop = document.body.getBoundingClientRect().top;
var divPosition = this.animationBounds.containerBounds[position];
var startPointInCurrentWindow = window.innerHeight * this.animationBounds[position];
return divPosition - distanceFromPageTop - startPointInCurrentWindow;
};
Scroller.prototype.animateLine = function () {
this.currentVisiblePosition = window.pageYOffset;
if (this.currentVisiblePosition < this.start) {
this.svg.style.strokeDashoffset = this.svgLength;
}
if (this.currentVisiblePosition > this.end) {
this.svg.style.strokeDashoffset = '0px';
}
if (this.currentVisiblePosition > this.start && this.currentVisiblePosition < this.end) {
this.svg.style.strokeDashoffset = this.distanceRemaining() * this.pixelsPerVerticalScroll() + 'px';
}
};
Scroller.prototype.distanceRemaining = function () {
return this.end - this.currentVisiblePosition;
};
Scroller.prototype.pixelsPerVerticalScroll = function () {
this.verticalDistance = this.end - this.start;
return this.svgLength / this.verticalDistance;
};
new Scroller({
'el': **document.getElementById('line')**,
'startPoint': .8,
'endPoint': .5
});
</script>
Loop over all the elements matching the selector.
var lines = document.querySelectorAll("#line, #line1, #line2");
for (var i = 0; i < lines.length; i++) {
new Scroller({
el: lines[i],
startPoint: .8,
endPoint: .5
});
}

Random pattern while animating simulated gradient in canvas element

This is a query about something that popped up while I was experimenting with the canvas element via javascript. I wanted to have an array of points that formed a gradient which moved with time, which works perfectly apart from a bizarre pattern that comes up (only after the first wave or more), which also changes according to the number of columns and rows in the canvas (changing the size of the points just makes the patterns bigger or smaller, it's always on the same pixels.
Here's a little demo of what I mean with a bit of interface for you to mess around with, an example of the changing patterns is if the number of rows is changed to 0.75x the number of columns from the original (i.e. 40 columns, 30 rows).
http://codepen.io/zephyr/pen/GpwwWB
Javascript:
String.prototype.hexToRGBA = function(a) {
function cutHex(h) {
return (h.charAt(0) == "#") ? h.substring(1, 7) : h
}
var r = parseInt((cutHex(this)).substring(0, 2), 16);
var g = parseInt((cutHex(this)).substring(2, 4), 16);
var b = parseInt((cutHex(this)).substring(4, 6), 16);
return 'rgba(' + r.toString() + ',' + g.toString() + ',' + b.toString() + ',' + a.toString() + ')';
}
CanvasRenderingContext2D.prototype.clearDrawRect = function(shape) {
this.clearRect(shape.position.x, shape.position.y, shape.size, shape.size);
this.fillStyle = shape.color.base;
this.fillRect(shape.position.x, shape.position.y, shape.size, shape.size);
}
CanvasRenderingContext2D.prototype.render = function(render) {
(function animate() {
requestAnimationFrame(animate);
render();
})();
}
CanvasRenderingContext2D.prototype.renderAndThrottleFpsAt = function(fps, render) {
var fpsInterval, startTime, now, then, elapsed;
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
(function animate() {
requestAnimationFrame(animate);
now = Date.now();
elapsed = now - then;
if (elapsed > fpsInterval) {
then = now - (elapsed % fpsInterval);
render();
}
})();
}
CanvasRenderingContext2D.prototype.pool = {};
CanvasRenderingContext2D.prototype.parsePoint = function(x, y, s, c) {
return {
color: c,
position: {
x: x,
y: y
},
size: s
}
}
CanvasRenderingContext2D.prototype.fillPointsPool = function(size, cols, rows, color) {
var i = cols;
var j = rows;
while(i--){
while(j--){
var x = i * size;
var y = j * size;
var a = (i * j) / (cols * rows);
var c = {
hex: color,
alpha: a,
dir: 1
};
if (typeof this.pool.points == 'undefined') {
this.pool.points = [this.parsePoint(x, y, size, c)];
} else {
this.pool.points.push(this.parsePoint(x, y, size, c));
}
}
j = rows;
}
}
CanvasRenderingContext2D.prototype.updatePointsPool = function(size, cols, rows, color) {
this.pool.points = [];
this.clearRect(0,0,this.canvas.width,this.canvas.height);
this.fillPointsPool(size, cols, rows, color);
}
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// Populate Points
var size = document.getElementById('size');
var cols = document.getElementById('cols');
var rows = document.getElementById('rows');
var color = document.getElementById('color');
ctx.fillPointsPool(size.value, cols.value, rows.value, color.value);
size.oninput = function(){
ctx.updatePointsPool(this.value, cols.value, rows.value, color.value);
}
cols.oninput = function(){
ctx.updatePointsPool(size.value, this.value, rows.value, color.value);
}
rows.oninput = function(){
ctx.updatePointsPool(size.value, cols.value, this.value, color.value);
}
color.oninput = function(){
ctx.updatePointsPool(size.value, cols.value, rows.value, this.value);
}
ctx.renderAndThrottleFpsAt(60, function(){
var i = 0;
var len = ctx.pool.points.length;
while (i<len) {
var point = ctx.pool.points[i];
// Change alpha for wave
var delta = 0.01;
point.color.alpha = point.color.alpha + (delta * point.color.dir);
if (point.color.alpha > 1) {
point.color.dir = -1;
} else if (point.color.alpha <= 0) {
point.color.dir = 1;
}
// Calculate rgba value with new alpha
point.color.base = point.color.hex.hexToRGBA(point.color.alpha);
ctx.clearDrawRect(point);
i++;
}
});
Do any of you have an idea of what's causing the pattern to appear, and any suggestions on a fix for this?
Note: I will be changing the updatePointsPool function
You are forgetting to clamp your alpha values when you change the direction. The small error in the alpha value accumulates slowly producing the unwanted artifacts you see as the animation progresses.
To fix add the top and bottom limits to alpha in the code just after you add delta direction to alpha.
if (point.color.alpha > 1) {
point.color.alpha = 1; // clamp alpha max
point.color.dir = -1;
} else if (point.color.alpha <= 0) {
point.color.alpha = 0; // clamp alpha min
point.color.dir = 1;
}

My javascript canvas map script and poor performance

Basically below is my script for a prototype which uses 128x128 tiles to draw a map on a canvas which user can drag to move around.
Script does work. However I have a few problems to be solved:
1. Poor performance and I can't figure out why.
2. I am missing a method to buffer the tiles before the actual drawing.
3. If you notice any other issues also that could help me to make things run more smoothly it would be fantastic.
Some explanations for the script:
variables
coordinates - Defines the actual images to be displayed. Image file names are type of '0_1.jpg', where 0 is Y and 1 is X.
mouse_position - As name says, is keeping record of mouse position.
position - This is a poorly named variable. It defines the position of the context drawn on canvas. This changes when user drags the view.
Any assistance would be appreciated greatly. Thank you.
var coordinates = [0, 0];
var mouse_position = [0, 0];
var position = [-128, -128];
var canvas = document.getElementById('map_canvas');
var context = canvas.getContext('2d');
var buffer = [];
var buffer_x = Math.floor(window.innerWidth/128)+4;
var buffer_y = Math.floor(window.innerHeight/128)+4;
var animation_frame_request = function() {
var a = window.requestAnimationFrame;
var b = window.webkitRequestAnimationFrame;
var c = window.mozRequestAnimationFrame;
var d = function(callback) {
window.setTimeout(callback, 1000/60);
}
return a || b || c || d;
}
var resizeCanvas = function() {
window.canvas.width = window.innerWidth;
window.canvas.height = window.innerHeight;
window.buffer_x = Math.floor(window.innerWidth/128)+4;
window.buffer_y = Math.floor(window.innerHeight/128)+4;
window.buffer = [];
for (row = 0; row < window.buffer_y; row++) {
x = [];
for (col = 0; col < window.buffer_x; col++) {
x.push(new Image());
}
window.buffer.push(x);
}
}
var render = function() {
animation_frame_request(render);
for (row = 0; row < window.buffer_y; row++) {
for (col = 0; col < window.buffer_x; col++) {
cy = window.coordinates[1]+row;
cx = window.coordinates[0]+col;
window.buffer[row][col].src = 'map/'+cy+'_'+cx+'.jpg';
}
}
for (row = 0; row < window.buffer_y; row++) {
for (col = 0; col < window.buffer_x; col++) {
window.context.drawImage(window.buffer[row][col],
window.position[0]+col*128,
window.position[1]+row*128, 128, 128);
}
}
}
var events = function() {
window.canvas.onmousemove = function(e) {
if (e['buttons'] == 1) {
window.position[0] += (e.clientX-window.mouse_position[0]);
window.position[1] += (e.clientY-window.mouse_position[1]);
if (window.position[0] >= 0) {
window.position[0] = -128;
window.coordinates[0] -= 1;
} else if (window.position[0] < -128) {
window.position[0] = 0;
window.coordinates[0] += 1;
}
if (window.position[1] >= 0) {
window.position[1] = -128;
window.coordinates[1] -= 1;
} else if (window.position[1] < -128) {
window.position[1] = 0;
window.coordinates[1] += 1;
}
render();
}
window.mouse_position[0] = e.clientX;
window.mouse_position[1] = e.clientY;
}
}
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('load', resizeCanvas, false);
window.addEventListener('mousemove', events, false);
resizeCanvas();
To get better performance you should avoid changing the src of img nodes and move them around instead.
A simple way to minimize the number of img nodes handled and modified (except for screen positioning) is to use an LRU (Least Recently Used) cache.
Basically you keep a cache of last say 100 image nodes (they must be enough to cover at least one screen) by using a dictionary mapping the src url to a node object and also keeping them all in a doubly-linked list.
When a tile is required you first check in the cache, and if it's already there just move it to the front of LRU list and move the img coordinates, otherwise create a new node and set the source or, if you already hit the cache limit, reuse the last node in the doubly-linked list instead. In code:
function setTile(x, y, src) {
var t = cache[src];
if (!t) {
if (cache_count == MAXCACHE) {
t = lru_last;
t.prev.next = null;
lru_last = t.prev;
t.prev = t.next = null;
delete cache[t.src]
t.src = src;
t.img.src = src;
cache[t.src] = t;
} else {
t = { prev: null,
next: null,
img: document.createElement("img") };
t.src = src;
t.img.src = src;
t.img.className = "tile";
scr.appendChild(t.img);
cache[t.src] = t;
cache_count += 1;
}
} else {
if (t.prev) t.prev.next = t.next; else lru_first = t.next;
if (t.next) t.next.prev = t.prev; else lru_last = t.prev;
}
t.prev = null; t.next = lru_first;
if (t.next) t.next.prev = t; else lru_last = t;
lru_first = t;
t.img.style.left = x + "px";
t.img.style.top = y + "px";
scr.appendChild(t.img);
}
I'm also always appending the requested tile to the container so that it goes in front of all other existing tiles; this way I don't need to remove old tiles and they're simply left behind.
To update the screen I just iterate over all the tiles I need and request them:
function setView(x0, y0) {
var w = scr.offsetWidth;
var h = scr.offsetHeight;
var iy0 = y0 >> 7;
var ix0 = x0 >> 7;
for (var y=iy0; y*128 < y0+h; y++) {
for (var x=ix0; x*128 < x0+w; x++) {
setTile(x*128-x0, y*128-y0, "tile_" + y + "_" + x + ".jpg");
}
}
}
most of the time the setTile request will just update the x and y coordinates of an existing img tag, without changing anything else. At the same time no more than MAXCACHE image nodes will be present on the screen.
You can see a full working example in
http://raksy.dyndns.org/tiles/tiles.html

Why do my values mutate inside the arrays?

I wrote a little test program, exploring my problem, and it works the way I expect it, printing "four, five, six".
var foo = function() {
console.log("just one more test")
var destination = new Array;
data = [ "four", "five" , "six" ]
var parent = [ 0, 1, 2 ];
var something;
parent.forEach(function(element) {
something = data[element];
destination.push(something);
})
destination.forEach(function (thing) {
console.log(thing);
})
}
foo();
But in my real code, when I push things on to my 'clickable' array, all of the entries mutate into the current value of the 'clicker' variable. There are 3 entries in my 'scheme_list', and they draw correctly, but as I try to build areas to click on, at each iteration of the loop "in the loop" prints the value just pushed on to the array for every instance. That is, the instances of 'clicker' already in the loop change to the current value of clicker. I'm scratching my head trying to understand the difference between my real code and my test code. Or, more to the point, how to fix my real code.
var layout_color_schemes = function(scheme_list) {
var canvas = document.getElementById('color_picker_canvas');
var ctx = canvas.getContext('2d');
var x_upper_left = 5;
var y_upper_left = 5;
var width = 200;
var height = 30;
var clickables = new Array;
var clicker = {};
clicker.rect = {};
clicker.rect.width = width;
clicker.rect.height = height;
scheme_list.forEach(function(row) {
var grad = ctx.createLinearGradient(0, 0, 100, 0);
var cscheme = jQuery.parseJSON(row.json);
cscheme.forEach(function(color_point) {
grad.addColorStop(color_point[0], 'rgb(' + color_point[1] + ','
+ color_point[2] + ',' + color_point[3] + ')');
})
ctx.fillStyle = grad;
ctx.fillRect(x_upper_left, y_upper_left, width, height);
clicker.rect.x = x_upper_left;
clicker.rect.y = y_upper_left;
clicker.scheme = cscheme;
clicker.name = row.name;
clickables.push(clicker);
printf("clickables size = %d", clickables.length)
for (index = 0; index < clickables.length; ++index) {
printf("Index is %d", index)
printf("in the loop %j", clickables[index])
}
ctx.fillStyle = 'black'
ctx.fillText(row.name, x_upper_left + width + 10, 5 + y_upper_left
+ (height / 2));
y_upper_left = y_upper_left + height + 10;
});
clickables.forEach(function(area) {
printf("before call clickable area = %j", area)
});
wire_clickables(clickables);
};
function wire_clickables(clickables) {
clickables.forEach(function(area) {
if (area.hasOwnProperty('rect')) {
printf("wiring a clickable %j", area);
$("#color_picker_canvas").mousemove(function(e) {
var inside = false;
var offsetX = e.pageX - $(this).position().left;
var offsetY = e.pageY - $(this).position().top;
if (area && contains(area.rect, offsetX, offsetY)) {
document.body.style.cursor = 'pointer'
}
else {
document.body.style.cursor = 'default'
}
})
}
})
}
function contains(rect, x, y) {
return (x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y
+ rect.height)
}
The clicker object exists outside of the loop, so all you are doing is pushing the same reference onto clickables. Instead, you want to push a copy of it. There are many ways to do this, but in your case this may be one of the simplest ways:
Replace
clickables.push(clicker);
with
clickables.push(JSON.parse(JSON.stringify(clicker));
Alternatively, move the clicker declaration and initialization inside the loop.

Categories

Resources