Fade coin in and out javascript canvas - javascript

I have a coin image coin.png I would like to appear and then fade up torwards the top of the canvas and then disappear but should be able to continuosly spawn randomly with the same behavior but im not sure how to do this with my current set up for example I am using my canvas in this manner
function writeMessage(canvas, message,x,y) {
var terminal = canvas.getContext('2d');
ClearCanvas();
terminal.font = "20px Comic Sans MS";
terminal.fillStyle = "rgb(0,255,1)";
terminal.textAlign = "center";
terminal.fillText(message, x, y);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
var canvas = document.getElementById("terminalCanvas");
var terminal = canvas.getContext("2d");
terminal.fillStyle = "#000000";
terminal.fillRect(0,0,canvas.width,canvas.height);
terminal.font = "20px Comic Sans MS";
terminal.fillStyle = "rgb(0,255,1)";
terminal.textAlign = "center";
terminal.fillText("Coding Idle Terminal", canvas.width/2, canvas.height/2);
$('#terminalCanvas').click(function(evt){
WriteToCanvas();
function WriteToCanvas(){
if(Game.Terminal.HTMLSupport == 1 && Game.Terminal.CSSSupport == 0){
var rand = Math.floor(Math.random() * 122) + 1;
var tag = htmltags[rand];
Game.Player.money += Game.Player.clickIncrement + (Game.Player.clickIncrement * Game.Player.codingGods/100);
Game.Player.exp += Game.Player.clickIncrement + (Game.Player.clickIncrement * Game.Player.codingGods/100);
Game.Player.clicksTotal += Game.Player.clickIncrement + + (Game.Player.clickIncrement * Game.Player.codingGods/100);
var mousePos = getMousePos(canvas,evt);
var message = tag;
writeMessage(canvas, message,mousePos.x,mousePos.y);
}else if(Game.Terminal.CSSSupport == 1 && Game.Terminal.JavascriptSupport == 0){
var tagList = htmltags.concat(csstags);
var tagListLength = tagList.length;
var rand = Math.floor(Math.random() * tagListLength) + 1;
var tagg = tagList[rand];
Game.Player.money += Game.Player.clickIncrement + (Game.Player.clickIncrement * Game.Player.codingGods/100);
Game.Player.exp += Game.Player.clickIncrement + (Game.Player.clickIncrement * Game.Player.codingGods/100);
Game.Player.clicksTotal += Game.Player.clickIncrement + + (Game.Player.clickIncrement * Game.Player.codingGods/100);
var mousePos = getMousePos(canvas,evt);
var message = tagg;
writeMessage(canvas, message,mousePos.x,mousePos.y);
}else if(Game.Terminal.JavascriptSupport == 1 && Game.Terminal.PHPSupport == 0){
var t1 = csstags.concat(javascripttags);
var tagList = htmltags.concat(t1);
var tagListLength = tagList.length;
var rand = Math.floor(Math.random() * tagListLength) + 1;
var tagg = tagList[rand];
Game.Player.money += Game.Player.clickIncrement + (Game.Player.clickIncrement * Game.Player.codingGods/100);
Game.Player.exp += Game.Player.clickIncrement + (Game.Player.clickIncrement * Game.Player.codingGods/100);
Game.Player.clicksTotal += Game.Player.clickIncrement + + (Game.Player.clickIncrement * Game.Player.codingGods/100);
var mousePos = getMousePos(canvas,evt);
var message = tagg;
writeMessage(canvas, message,mousePos.x,mousePos.y);
}else if(Game.Terminal.PHPSupport == 1){
var t1 = csstags.concat(javascripttags);
var t2 = t1.concat(t1);
var tagList = htmltags.concat(t2);
var tagListLength = tagList.length;
var rand = Math.floor(Math.random() * tagListLength) + 1;
var tagg = tagList[rand];
Game.Player.money += Game.Player.clickIncrement + (Game.Player.clickIncrement * Game.Player.codingGods/100);
Game.Player.exp += Game.Player.clickIncrement + (Game.Player.clickIncrement * Game.Player.codingGods/100);
Game.Player.clicksTotal += Game.Player.clickIncrement + + (Game.Player.clickIncrement * Game.Player.codingGods/100);
var mousePos = getMousePos(canvas,evt);
var message = tagg;
writeMessage(canvas, message,mousePos.x,mousePos.y);
}
}
});
function ClearCanvas(){
terminal.clearRect(0,0,canvas.width,canvas.height);
terminal.fillStyle = "#000000";
terminal.fillRect(0,0,canvas.width,canvas.height);
}
Now I would much prefer to have a seperate function I can call perhaps
function coinRandom(){
var number = Math.floor(Math.random() * 100) + 1;
if(number == 56){
//Draw coin to screen and other stuff
Game.Player.relics += 1;
}else{
//Do nothing
}
}
The biggest part of the function is it should get the mousePos.x and mousePos.y and draw the coin there and then from there fade out torwards the top of the canvas

You will need to establish a list of coins that are moving on the screen. The coins will need to be animated during each frame of the game. The function you desire will then add coins to the list at the appropriate time. You will need a second function that is called during each frame of the game that will check the list of coins, then animate and draw a coin for each entry in the list.
Here is a fiddle that uses random numbers to put the coin on the screen:
https://jsfiddle.net/05t6v8sL/
var rW = 400;
var rH = 500;
var coinImage = getCoinImage();
var coinsOnScreen = [];
var maxCoins = 50;
var risingSpeed = 200; //pixels per second...
var lastAnimationTime = 0;
function doDraw() {
var can = document.getElementById("myCanvas");
can.width = rW;
can.height = rH;
var context = can.getContext("2d");
//Erase the canvas
context.fillStyle="#FFFFFF";
context.fillRect(0, 0, rW, rH);
//if there are less than maxCoins on the screen, add a new coin to a random position:
if (coinsOnScreen.length<maxCoins) {
//generate random x and y coordinates:
var newX = Math.floor(Math.random() * rW) + 1;
var newY = Math.floor(Math.random() * rH) + 1;
var newCoin = {
x: newX,
y: newY,
stl: 4
};
coinsOnScreen.push(newCoin);
}
//Now draw the coins
if (lastAnimationTime != 0) {
var deltaTime = new Date().getTime() - lastAnimationTime;
var coinRisePixels = Math.floor((deltaTime * risingSpeed)/1000);
var survivingCoins = [];
for (var i=0;i<coinsOnScreen.length;i++) {
var coin = coinsOnScreen[i];
coin.y = coin.y - coinRisePixels;
//the stl variable controlls the alpha of the image
coin.stl = (coin.stl * 1000 - deltaTime)/1000;
if (coin.y+50 > 0) {
var alpha = coin.stl/6;
context.save();
context.globalAlpha=alpha;
context.drawImage(coinImage, coin.x, coin.y);
context.restore();
//this coin is still on the screen, so promote it to the new array...
survivingCoins.push(coin);
}
}
coinsOnScreen = survivingCoins;
}
lastAnimationTime = new Date().getTime();
//Wait, and then call this function again to animate:
setTimeout(function() {
doDraw();
}, 30);
}
doDraw();
function getCoinImage() {
var image = new Image(50, 50);
image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAA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YAS33UABAAOFqVYFaUKEMkKQGDqU/0EExUEZmZEJNGrgwSO93YEX3C5jRuVmJiwVwK5gTIgb2BCLUn4LdBPIMFgAQQPiah3eBmv2ABt2EWQYyGNQBAlnExoGW1nGMDLIilUz/8SRDcD5ih5gNSkqgEU8UT/xnCIA2p7ACgABiIpA8bgMN8AUaeByWZ0CW/PwKYYPnx9mh/Rg0D8AwrLSBiSNPBsH6QKAxXVC3ABQbILP/Io3mA9VcBmI/8PQBHgAQQITHLyCecQfiNiD+CRu6BA0Y/ITOr4Im+0EOAdHgRQJoLV3k0okRWpzC9XBB8xPQrF9fEcUxUP1/IJ4K5LgA5c8RciZAADE+mog/4/1HarIA+XZAfheQZY5R1kPrBlBxyciE1ORGtgxpFcT/v4hZKwak1gO0v3QeSNcAOdsYocHNyIi/gAEIIFJXBx2CNmMSgbZlAS3Ugvf+YcM/jEhLP5jgqyfgIx7Ia0sYkZZKQX18D0jNBPJnQHs7RAOAACI1RhDjXsDaH0j5A1lRQLY9tHlIDvgJdPgxIL0CiNcCPfcWY20YETECEECUeASRbP4zaILaPUC+EZCtDmQD27oMvDhMBeWsh0BH3QTSF4BuOwBkX4LFCSO2RW5EeAQgwACQYpcXuHTdswAAAABJRU5ErkJggg==";
return image;
}
When each frame is drawn, the code will add a new coin to the coinsOnScreen array unless maxCoins count has been reached.
The number of pixels the coin will rise depends on the deltaTime of the frame rate. The pixels are subtracted from each coin in each frame until the coin is off the screen, at this point, the coin should be removed from the screen.
The alpha value of the coin is controlled by the "stl" variable that is assigned to each coin.
The effect you describe reminds me of when Mario grabs a coin and it briefly flies in the air. If this is more of the effect you desire, then instead of simply subtracting pixels from the y coordinate of the coin, you would calculate its path along a projectile function, like a parabola.

Related

Drag object around a half circle on mouse over - Adobe Animate HTML5 Canvas

I have the following code in Adobe Animate HTML5 Canvas using JavaScript/Easel.js/Create.js. The code enables an object to be dragged around a circle.
I now want to change this to function for a half circle, the top half. The object needs to be moved CW and CCW, and stop at the ends of the half circle (so backwards and forwards, but not right around a circle).
stage.enableMouseOver();
var knob_X = 454;
var knob_Y = 169;
var radius = 80;
var streakAngle;
root.streakRotatorKnob.addEventListener("mouseover", mouseOverKnob.bind(this));
root.streakRotatorKnob.x = knob_X + radius * Math.cos(0);
root.streakRotatorKnob.y = knob_Y + radius * Math.sin(0);
function mouseOverKnob(evt)
{
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function moveF(evt) {
var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
var atan_knob = Math.atan2(evt.currentTarget.y, evt.currentTarget.x);
evt.currentTarget.x = knob_X + radius * Math.cos(rads);
evt.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
console.log(atan_knob);
streakAngle = Math.round(((rads * 180 / Math.PI) * 100) / 100);
if (leye == true) {
root.streakMainLeft.rotation = streakAngle + 90;
} else if (reye == true) {
root.streakMainRight.rotation = streakAngle + 90;
}
root.streakAngle.text = streakAngle + "\u00B0";
}
The video link below in the first half of the video shows what I currently have working in this code.
The last half of the video shows what I want.
I would change the circle graphic to a half circle...
https://youtu.be/781GzUulX1c
I can't understand exactly what you want.
It would be better if you shared the source file directly.
I prepared an example, can you download and examine it?
we.tl/t-oflBkdma0o
I also convey that I cannot edit through your codes.
stage.enableMouseOver();
var root = this;
var knob_X = 454;
var knob_Y = 169;
var radius = 80;
var streakAngle;
var leye = true;
root.streakRotatorKnob.addEventListener("mouseover", mouseOverKnob.bind(this));
root.streakRotatorKnob.x = knob_X + radius * Math.cos(0);
root.streakRotatorKnob.y = knob_Y + radius * Math.sin(0);
function mouseOverKnob(evt)
{
root.streakRotatorKnob.addEventListener("pressmove", moveF);
}
function moveF(evt) {
var rads = Math.atan2(stage.mouseY/stage.scaleY - knob_Y, stage.mouseX/stage.scaleX - knob_X);
var atan_knob = Math.atan2(evt.currentTarget.y, evt.currentTarget.x);
streakAngle = Math.round(((rads * 180 / Math.PI) * 100) / 100);
if(streakAngle>=-90 && streakAngle<=90)
{
evt.currentTarget.x = knob_X + radius * Math.cos(rads);
evt.currentTarget.y = knob_Y + radius * Math.sin(rads);
}
stage.update();
//console.log("atan_knob: "+atan_knob);
/*
if (leye == true) {
root.streakMainLeft.rotation = streakAngle + 90;
} else if (reye == true) {
root.streakMainRight.rotation = streakAngle + 90;
}
*/
console.log("streakAngle: " +streakAngle);
//root.streakAngle.text = streakAngle + "\u00B0";
}

JavaScript - Show link based on spinner

I found this js spinner and I like how it has the counter at the end. It counts down from 15 seconds. I was wondering if it would be possible to make it so that if you land on geography for example it counts down 5 seconds and then redirects you to a separate website. And history would bring you to a different link and so on. Thanks
JavaScript
var colors = ["#ffff00" , "#1be11b", "#0000ff", "#7e7e7e", "#8a2be2", "#006400", "#2980B9", "#E74C3C"];
// NEED to pre load this data prior
var prize_descriptions = ["GENERAL", "GEOGRAPHY", "HISTORY", "ARTS", "SCIENCE", "SPORTS", "RELIGION", "MEDIA"];
var current_user_status = {};
var startAngle = 0;
var arc = Math.PI / 4;
var spinTimeout = null;
var spinArcStart = 10;
var spinTime = 0;
var spinTimeTotal = 0;
var current_user_status = null;
var spin_results = null;
var wheel;
var counter, tt;
function drawSpinnerWheel() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var outsideRadius = 200;
var textRadius = 160;
var insideRadius = 125;
wheel = canvas.getContext("2d");
wheel.clearRect(0, 0, 500, 500);
wheel.strokeStyle = "#ecf0f1";
wheel.lineWidth = 5;
wheel.font = '12px Helvetica, Arial';
for (var i = 0; i < 8; i++) {
var angle = startAngle + i * arc;
wheel.fillStyle = colors[i];
wheel.beginPath();
wheel.arc(250, 250, outsideRadius, angle, angle + arc, false);
wheel.arc(250, 250, insideRadius, angle + arc, angle, true);
wheel.stroke();
wheel.fill();
wheel.save();
wheel.shadowOffsetX = -1;
wheel.shadowOffsetY = -1;
wheel.shadowBlur = 0;
wheel.shadowColor = "rgb(220,220,220)";
wheel.fillStyle = "#ecf0f1";
wheel.translate(250 + Math.cos(angle + arc / 2) * textRadius, 250 + Math.sin(angle + arc / 2) * textRadius);
wheel.rotate(angle + arc / 2 + Math.PI / 2);
var text = prize_descriptions[i];
if (text === undefined) text = "Not this time!";
wheel.fillText(text, -wheel.measureText(text).width / 2, 0);
wheel.restore();
}
//Arrow
wheel.fillStyle = "#ecf0f1";
wheel.beginPath();
wheel.moveTo(250 - 4, 250 - (outsideRadius + 5));
wheel.lineTo(250 + 4, 250 - (outsideRadius + 5));
wheel.lineTo(250 + 4, 250 - (outsideRadius - 5));
wheel.lineTo(250 + 9, 250 - (outsideRadius - 5));
wheel.lineTo(250 + 0, 250 - (outsideRadius - 13));
wheel.lineTo(250 - 9, 250 - (outsideRadius - 5));
wheel.lineTo(250 - 4, 250 - (outsideRadius - 5));
wheel.lineTo(250 - 4, 250 - (outsideRadius + 5));
wheel.fill();
}
}
function spin() {
$("#spin").unbind('click');
$("#spin").attr("id", "nospin");
document.getElementById('timer').innerHTML = " ";
document.getElementById('category').innerHTML = " ";
spinMovement = Math.floor(Math.random() * 20) + prize_descriptions.length * 2;
spinAngleStart = 1 * 10 + spinMovement;
spinTime = 0;
spinTimeTotal = Math.floor(Math.random() * 4) * Math.floor(Math.random() * 6) + Math.floor(Math.random() * 8) * Math.floor(Math.random() * 2000) + 2000;
console.log(spinMovement + " - " + spinTimeTotal);
rotateWheel();
}
function rotateWheel() {
spinTime += 30;
if (spinTime >= spinTimeTotal) {
stopRotateWheel();
return;
}
var spinAngle = spinAngleStart - easeOut(spinTime, 0, spinAngleStart, spinTimeTotal);
startAngle += (spinAngle * Math.PI / 180);
drawSpinnerWheel();
spinTimeout = setTimeout('rotateWheel()', 30);
}
function stopRotateWheel() {
clearTimeout(spinTimeout);
var degrees = startAngle * 180 / Math.PI + 90;
var arcd = arc * 180 / Math.PI;
var index = Math.floor((360 - degrees % 360) / arcd);
wheel.save();
wheel.font = '30px "Homestead-Inline", Helvetica, Arial';
var text = prize_descriptions[index];
//wheel.fillText(text, 250 - wheel.measureText(text).width / 2, 250 + 10);
wheel.restore();
document.getElementById('timer').innerHTML = "15";
document.getElementById('category').innerHTML = "Your Category is: " + text;
counter = 15;
tt=setInterval(function(){startTime()},1000);
}
function easeOut(t, b, c, d) {
var ts = (t /= d) * t;
var tc = ts * t;
return b + c * (tc + -3 * ts + 3 * t);
}
drawSpinnerWheel();
function startTime() {
if(counter == 0) {
clearInterval(tt);
$("#nospin").attr("id", "spin");
$("#spin").bind('click', function(e) {
e.preventDefault();
spin();
});
} else {
counter--;
}
document.getElementById('timer').innerHTML = counter;
}
$("#spin").bind('click', function(e) {
e.preventDefault();
spin();
});
To see it in action click here
It seems that all your changes should be made in the function stopRotateWheel() and startTime()
When the function is called, a variable called text holds the result ("Geography" or "Science", etc.).
From that, we can perform conditions based on the value of text and determine the total time of countdown, plus the link when the countdown expires.
Something like this:
function stopRotateWheel() {
clearTimeout(spinTimeout);
var degrees = startAngle * 180 / Math.PI + 90;
var arcd = arc * 180 / Math.PI;
var index = Math.floor((360 - degrees % 360) / arcd);
wheel.save();
wheel.font = '30px "Homestead-Inline", Helvetica, Arial';
var text = prize_descriptions[index];
//wheel.fillText(text, 250 - wheel.measureText(text).width / 2, 250 + 10);
wheel.restore();
document.getElementById('timer').innerHTML = "15";
document.getElementById('category').innerHTML = "Your Category is: " + text;
/*do an if else*/
if(text=="Geography")
{
counter = 5;
tt=setInterval(function(){startTime("www.geography.com")},1000);
/*countdown, and when timer expires... go to another link*/
}
else if (text=="Science")
{
//do the same as above :)
}
}
notice the code startTime("www.geography.com")? that's because we also modify function startTime to accept a parameter (in this case, the website) so that when the countdown is finished the webpage goes to that link :)
function startTime(gotoLink) {
if(counter == 0) {
/*go to that link */
window.location.replace(gotoLink)
} else {
counter--;
}
document.getElementById('timer').innerHTML = counter;
}
try it out!

Javascript animation easing

I have a function which moves my canvas using an ease in aspect. The problem how ever is the canvas animation doesn't work. It just scrolls too far and what appears to be too fast as well.
This is my function which moves the camera to the location the user clicked on the canvas:
function moveCamera(e,parent){
clearInterval(parent.scroll);
var mouseData = mousePos(evt,parent); //get x:y relative to element
var initial = {'x':el.width/2,'y':el.height/2},
target = {'x':mouseData.x,'y':mouseData.y},
deltaX = target.x-initial.x,
deltaY = target.y-initial.y,
timeStart = Date.now(),
timeLength = 800,
x,y,deltaTime;
function update(){
function fraction(t){
x = (target.x - initial.x) - (t*deltaX),
y = (target.y - initial.y) - (t*deltaY);
camera.x -= x;
camera.y -= y;
}
function easing(x) {
return 0.5 + 0.5 * Math.sin((x - 0.5) * Math.PI);
}
deltaTime = (Date.now() - timeStart) / timeLength;
if (deltaTime > 1) {
fraction(1);
} else {
fraction(easing(deltaTime));
}
}
parent.scroll = setInterval(update, 10);
}
I have attatched a JSFiddle of the issue demonstrated: http://jsfiddle.net/p5xjmLay/ simply click on the canvas to scroll to that position, and you will see it goes a bit crazy.
I am wondering how to solve this so the camera offset changes correctly each time?
I changed a little bit your version and it seems that it is working, please try this:
var el = document.getElementById('canvas'),
initial = {'x':el.width/2,'y':el.height/2},
ctx = el.getContext('2d'),
camera = {'x':el.width/2,'y':el.height/2},
box = {'x':0,'y':0};
var x,y,deltaTime;
el.addEventListener('mousedown',function(e){moveCamera(e,this);},false);
function moveCamera(e,parent){
clearInterval(parent.scroll);
var mouseData = mousePos(e,parent);
target = {'x':mouseData.x,'y':mouseData.y},
deltaX = target.x-initial.x,
deltaY = target.y-initial.y,
timeStart = Date.now(),
timeLength = 800;
function update(){
function fraction(t){
x = target.x - (initial.x + (t*deltaX)),
y = target.y - (initial.y + (t*deltaY));
if (Math.abs(camera.x + x - target.x) > Math.abs(camera.x - target.x)) {
camera.x = target.x;
initial.x = target.x;
} else {
camera.x += x;
}
if (Math.abs(camera.y + y - target.y) > Math.abs(camera.y - target.y)) {
camera.y = target.y;
initial.y = target.y;
} else {
camera.y += y;
}
}
function easing(x) {
return 0.5 + 0.5 * Math.sin((x - 0.5) * Math.PI);
}
deltaTime = (Date.now() - timeStart) / timeLength;
if (deltaTime > 1) {
fraction(1);
} else {
fraction(easing(deltaTime));
}
draw();
}
parent.scroll = setInterval(update, 200);
}
function mousePos(evt,el){
var offsetX = 0,
offsetY = 0;
do{
offsetX += el.offsetLeft - el.scrollLeft;
offsetY += el.offsetTop - el.scrollTop;
}while(el = el.offsetParent){
return {'x':evt.pageX - offsetX, 'y':evt.pageY - offsetY}
}
}
function draw(){
ctx.clearRect(0,0,el.width,el.height);
ctx.save();
ctx.translate(camera.x,camera.y);
ctx.beginPath();
ctx.rect(box.x-25, box.y-25,50,50);
ctx.fillStyle = 'red';
ctx.fill();
ctx.restore();
}
draw();

Positioning mesh in three.js

I m trying to understand how i can positioning my cubes in the canvas.
But i don't understand how positioning work.
I m looking a way to detect if my mesh meet the limit of the canvas. But what is the unit of position.x or position.y ?
And what is the relation between the canvas width , height and meshs on in the canvas?
Thanks.
var geometry = new Array(),material = new Array(),cube = new Array();
var i = 0;
for(i=0; i < 10;i++){
geometry[i] = new THREE.BoxGeometry(1,1,1);
material[i] = new THREE.MeshBasicMaterial({ color: 0x33FF99 });
cube[i] = new THREE.Mesh(geometry[i], material[i]);
scene.add(cube[i]);
}
camera.position.z = 5;
var render = function () {
requestAnimationFrame(render);
var xRandom = 0;
var yRandom = 0;
var zRandom = 0;
var sens = 1;
for (i = 0; i < cube.length ; i++) {
document.getElementById('widthHeight').innerHTML = " " + window.innerHeight + " " + window.innerWidth + "<br> x:" + cube[i].position.x + " <br> y:" + cube[i].position.y + " <br> z:" + cube[i].position.z;
xRandom = (Math.random() * 0.010 + 0.001) * sens;
yRandom = (Math.random() * 0.010 + 0.001) * sens;
zRandom = (Math.random() * 0.010 + 0.001) * sens;
cube[i].position.setX(xRandom + cube[i].position.x);
cube[i].position.setY(yRandom + cube[i].position.y);
cube[i].position.setZ(zRandom + cube[i].position.z);
cube[i].rotation.x += 0.0191;
cube[i].rotation.y += 0.0198;
}
renderer.render(scene, camera);
};
render();
i added a PlaneGeometry and some tests to detect if cubes reach limit x or y of the new PlaneGeometry.
var geometry = new Array(),material = new Array(),cube = new Array();
var i = 0;
var planeMap = new THREE.PlaneGeometry(100, 100);
var materialMap = new THREE.MeshBasicMaterial({ color: 0xCE0F0F });
var map = new THREE.Mesh(planeMap,materialMap);
scene.add(map);
for(i=0; i < 5; i++){
geometry[i] = new THREE.BoxGeometry(3,3,3);
material[i] = new THREE.MeshBasicMaterial({ color: 0x336699 });
cube[i] = new THREE.Mesh(geometry[i], material[i]);
scene.add(cube[i]);
}
camera.position.z = 100;
var render = function () {
requestAnimationFrame(render);
var xRandom = 0,yRandom = 0,zRandom = 0,x=0,y=0,z=0;
var sensX = 1, sensY = 1, sensZ = 1;
var widthHeight = document.getElementById('widthHeight');
for (i = 0; i < cube.length ; i++) {
if (cube[i].geometry.type == "BoxGeometry") {
widthHeight.innerHTML = " " + window.innerHeight + " " + window.innerWidth + "<br> x:" + cube[i].position.x + " <br> y:" + cube[i].position.y + " <br> z:" + cube[i].position.z;
var currentCube = cube[i].position;
var widthCube = cube[i].geometry.parameters.width;
var heightCube = cube[i].geometry.parameters.height;
x = currentCube.x;
y = currentCube.y;
z = currentCube.z;
if (x >= ((map.geometry.parameters.width / 2) - widthCube)) {
sensX = -1;
}
if (x <= ((map.geometry.parameters.width / 2) - widthCube)*-1) {
sensX = 1;
}
if (y >= ((map.geometry.parameters.height / 2) - heightCube)) {
sensY = -1;
}
if (y <= ((map.geometry.parameters.height / 2) - heightCube)*-1) {
sensY = 1;
}
xRandom = (Math.random() * 0.650 + 0.001) * sensX * (i + 1);
yRandom = (Math.random() * 0.850 + 0.001) * sensY * (i + 1);
//zRandom = (Math.random() * 0.450 + 0.001) * sensZ * (i + 1);
cube[i].position.setX(xRandom + x);
cube[i].position.setY(yRandom + y);
cube[i].position.setZ(zRandom + z);
cube[i].rotation.x += 0.01;
cube[i].rotation.y += 0.01;
}
}
In three.js you are working with a 3D space, the scene. The x,y,z coordinates are in that space. Similar to the real world, you can think of it as a room with some objects in it.
What gets shown on the canvas in 2D is how your camera sees a particular view to that scene. You can observe this by modifying the z coordinate of the camera position which you have in your code. This is again similar to taking a photo with a real camera of a room with some objects.
So the relation of the 3D object position and where they show in the canvas depend on the camera view. Three.js can tell you where some 3D position is projected in the 2D view -- for details and an example, see the answer there: Converting 3D position to 2d screen position [r69!]

A relative rotation in an animation

I have a problem with Raphael.js. I want to rotate the "compassScale" - set in the following code - in a relative manner.
This works for the paths, but all the texts "animate" to the absolute rotation of 30 degree. I want them to rotate to the 30 degrees relative from their actual positions.
var compassScale = paper.set();
var centerX = 200;
var centerY = 200;
var radius = 195;
var compasCircle = paper.circle(centerX, centerY, radius);
for(var i = 0; i < 360; i++) {
var winkelRad = i * (Math.PI/180)
var xStart = centerX + Math.sin(winkelRad) * radius;
var yStart = centerY + Math.cos(winkelRad) * radius;
var diff = 6;
if(i % 10 === 0){
compassScale.push(paper.text(centerX, centerY - radius + 18, i).rotate(i, centerX, centerY, true));
diff = 12;
} else if(i % 5 === 0) {
diff = 8;
}
var xEnd = centerX + Math.sin(winkelRad) * (radius - diff);
var yEnd = centerY + Math.cos(winkelRad) * (radius - diff);
compassScale.push(paper.path("M" + xStart + " " + yStart + " L" + xEnd + " " + yEnd));
}
compassScale.animate({rotation:"30 " + centerX + " " + centerY}, 5000);
Like you said, the problem is that you're animating all elements to 30 degrees, not their current rotation + 30 degrees. It's actually quite simple once you think of it that way. Here is your revised code that works:
var compassScale = paper.set();
var texts = []; // array to hold the text elements
var centerX = 200;
var centerY = 200;
var radius = 195;
var compasCircle = paper.circle(centerX, centerY, radius);
for(var i = 0; i < 360; i++) {
var winkelRad = i * (Math.PI/180)
var xStart = centerX + Math.sin(winkelRad) * radius;
var yStart = centerY + Math.cos(winkelRad) * radius;
var diff = 6;
if(i % 10 === 0){
texts.push(paper.text(centerX, centerY - radius + 18, i).rotate(i, centerX, centerY, true));
diff = 12;
} else if(i % 5 === 0) {
diff = 8;
}
var xEnd = centerX + Math.sin(winkelRad) * (radius - diff);
var yEnd = centerY + Math.cos(winkelRad) * (radius - diff);
compassScale.push(paper.path("M" + xStart + " " + yStart + " L" + xEnd + " " + yEnd));
}
compassScale.animate({rotation:"30 " + centerX + " " + centerY}, 5000);
// loop through the text elements, adjusting their rotation by adding 30 to their individual rotation
for (var i = 0, l = texts.length; i < l; i += 1) {
// node.attr("rotation") returns something like 50 200 200, so we have to split the string and grab the first number with shift
texts[i].animate({rotation: (30 + +texts[i].attr("rotation").split(" ").shift()) + " " + centerX + " " + centerY}, 5000);
}
Just a quick observation:
Looks like "Rotation" isn't part of the Atrr anymore since ver 2, so you can't use it in "animate", but you can replace that with "transform: "r" + (some degree)"..
eg:
element.animate( {transform: "r" + (-90)}, 2000, 'bounce');

Categories

Resources