I have this JavaScript code for snow falling effect. It's working really nice,
but I decided to create a snow falling on web page text. I have tried, but not getting how to do it.
How to make snow fall on that "I love you" text? http://jsfiddle.net/DgrxX/22/
I have already seen in VB6 code where snow fall on text. If it is possible in Visual Basic 6 seven years ago, why not today in JavaScript or CSS3 or jQuery?
function vp(woh)
{
var viewportwidth;
var viewportheight;
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
}
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
viewportwidth = document.documentElement.clientWidth,
viewportheight = document.documentElement.clientHeight
}
else
{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
if (woh == 'w')
{
return viewportwidth;
}
else if (woh == 'h')
{
return viewportheight;
}
else
{
return false;
}
}
function snowflake()
{
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = Math.random()*2;
this.color = "white";
var tobefallingSpeed = Math.random() * 100;
this.fallingSpeed = tobefallingSpeed + 30;
}
function render()
{
ctx.clearRect(0,0,canvas.width, canvas.height);
for (b=0;b<snowflakes;b++)
{
sf[b].y+=0.4;
if(sf[b].y> canvas.height){
sf[b].y = 0;
}
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(sf[b].x,sf[b].y,sf[b].radius,sf[b].radius);
}
}
function main()
{
now = Date.now();
delta = now - then;
render();
then = now;
}
then = Date.now();
var int = self.setInterval(main,1);
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = vp('w');
canvas.height = vp('h');
document.body.appendChild(canvas);
var numberofSnowflakes = 100;
var sf = [];
for (i=0;i<numberofSnowflakes;i++)
{
sf[i] = new snowflake();
snowflakes = i;
}
Okay so I have seen a few answers but the asker wants the snow to be exclusively piling up on the text. Exact piling (according to the snow in background) would be really very difficult but I would like to suggest a (maybe complex) working method.
Make images.
A lots of them. With the text 'I love You' and contents of snow different in each. This maybe similar to creating picture frames from a video.
Define a div. Change your picture every x seconds, where x depends on number of images you have made.
You can use the following code for changing image:
function change_background( new_image_source ) {
var myimage = $( '#myimage' );
myimage.attr( 'src', new_image_source );
setTimeout( function () {
change_background( 'new image source here' );
}, 100);
}
This code will change the image after 0.1. This can hopefully give you the required effect but you will need to make a lot of pictures that differ slightly. I would make lots of pictures for my gf (if I had one).
Related
Some context:
I'm working on a Chrome Extension where the user can launch it via default "popup.html", or if the user so desires this Extension can be detached from the top right corner and be used on a popup window via window.open
This question will also apply for situations where users create a Shortcut for the extension on Chrome via:
"..." > "More tools" > "Create Shortcut"
Problem:
So what I need is for those cases where users use the extension detached via window.open or through a shortcut, when navigating through different options, for the Height of the window to be resized smoothly.
I somewhat achieve this but the animation is clunky and also the final height is not always the same. Sometimes I need to click twice on the button to resize too because 1 click won't be enough. Another issue is there is also some twitching of the bottom text near the edge of the window when navigating.
Here's what I got so far:
(strWdif and strHdif are used to compensate for some issues with CSS setting proper sizes which I haven't figured out yet.)
const popup = window;
function resizeWindow(popup) {
setTimeout(function () {
var strW = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var height = window.innerHeight;
console.log("Window Height: ", height, "CSS Height: ", bodyTargetHeight);
var timer = setInterval(function () {
if (height < bodyTargetHeight) {
popup.resizeTo(bodyTargetWidth, height += 5);
if (height >= bodyTargetHeight) {
clearInterval(timer);
}
} else if (height > bodyTargetHeight) {
popup.resizeTo(bodyTargetWidth, height -= 5);
if (height <= bodyTargetHeight) {
clearInterval(timer);
}
} else {
clearInterval(timer);
}
}, 0);
}, 0400);
}
Question:
Is there a way to make this more responsive, and smooth and eliminate all the twitching and clunkiness?
I guess the issue might be that I am increasing/diminishing by 5 pixels at a time but that is the speed I need. Maybe there is another way to increase/decrease by 1px at a faster rate? Could this be the cause of the twitching and clunkiness?
Also, I should add that troubleshooting this is difficult because the browser keeps crashing so there is also a performance issue sometimes when trying different things.
EDIT:
Another option using resizeBy:
function animateClose(time) {
setTimeout(function () {
var strW = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var w = window.innerWidth; //Get window width
var h = window.innerHeight; //Get window height
var loops = time * 0.1; //Get nb of loops
var widthPercentageMinus = (w / loops) * -0;
var heightPercentageMinus = (h / loops) * -1;
var widthPercentagePlus = (w / loops) * +0;
var heightPercentagePlus = (h / loops) * +1;
console.log("Window Height: ", h, "CSS Height: ", bodyTargetHeight);
var loopInterval = setInterval(function () {
if (h > bodyTargetHeight) {
window.resizeBy(widthPercentageMinus, heightDecrheightPercentageMinuseasePercentageMinus);
} else if (h < bodyTargetHeight) {
window.resizeBy(widthPercentagePlus, heightPercentagePlus);
} else {
clearInterval(loopInterval);
}
}, 1);
}, 0400);
}
This one is a bit more smooth but I can't make it stop at the desired Height. It also is not differentiating between resizing up or down, also crashes the browser sometimes.
maybe with requestAnimationFrame
try something like this (not tested):
function resizeWindow(popup) {
var gcs = getComputedStyle(window.document.querySelector(".body_zero"));
var strW = gcs.getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = gcs.getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var height = window.innerHeight;
console.log("Window Height: ", height, "CSS Height: ", bodyTargetHeight);
window.myRequestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame;
var hStep = 2; //choose the step. Must be an integer
function internalFunc() {
if (Math.abs(height - bodyTargetHeight) > hStep) {
if (height < bodyTargetHeight)
hStep *= 1;
else if (height > bodyTargetHeight)
hStep *= -1;
popup.resizeBy(0, hStep);
height += hStep;
window.myRequestAnimationFrame(internalFunc)
} else
popup.resizeBy(0, bodyTargetHeight - height)
}
popup.resizeTo(bodyTargetWidth, height);
window.myRequestAnimationFrame(internalFunc)
}
<html>
<head>
<script>
const bodyTargetWidth = 150;
const bodyTargetHeight = 250; //target height
var height; //height at beginning
window.myRequestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;
var hStep = 5; //choose the step. Must be an integer
var dir;
var myPopup;
function doResize() {
function internalFunc() {
console.log('height: ', height) ;
if (Math.abs(height - bodyTargetHeight) > hStep) {
dir = Math.sign(bodyTargetHeight - height);
myPopup.resizeBy(0, dir * hStep);
height += dir * hStep;
window.myRequestAnimationFrame(internalFunc)
} else
myPopup.resizeBy(0, bodyTargetHeight - height)
}
if (!myPopup || myPopup?.closed) {
myPopup = window.open("about:blank", "hello", "left=200,top=200,menubar=no,status=no,location=no,toolbar=no");
height = 150;
myPopup.resizeTo(bodyTargetWidth, height);
} else {
myPopup.focus();
height = myPopup.outerHeight
}
myPopup.resizeTo(bodyTargetWidth, height);
window.myRequestAnimationFrame(internalFunc)
}
document.addEventListener('DOMContentLoaded', _ => document.getElementById('myBtn').addEventListener('click', doResize))
</script>
</head>
<body>
<button type="button" id="myBtn">Create popup<br>\<br>Reset popup height</button><br>
<p>First create the popup, then change popup height and click the button above again</p>
</body>
</html>
I'm experimenting with the following code where images flip through in a canvas.
If I put the canvas, let's say at the middle of my page, I was wondering if there's a way to only make the images flip through once the viewer gets to that specific section of the page.
Right now, from the looks of it, the images start flipping through right at the top of the page, immediately when you scroll down. By the time you get to the middle of the page where the actual canvas is, the images have already finished flipping through, and it's stopped on the last frame.
I assume I have to set the function to only trigger after the user scrolls to a specific number of pixels on the Y-axis? What's the best way to do so?
Please see code below.
Thanks!
var images = new Array();
var currentLocation = 0;
var totalImages = 200;
for (var i = 1; i < totalImages; i++) {
var img = new Image;
var slug = '000' + i;
img.src = 'https://s3.amazonaws.com/clearmotion/hero/high-min/frame' + slug.slice(-3) + '-low.jpg'
images.push(img);
}
var c = document.getElementById("background");
var ctx = c.getContext("2d");
var mouseWheel = function() {
var newLocation = null;
window.addEventListener('wheel', function(e) {
e.preventDefault(); // No scroll
// update our variable at high frequency
var delta = Math.max(-1, Math.min(1, e.deltaY));
if (delta == -1) currentLocation += 1;
if (delta == 1) currentLocation -= 1;
if (currentLocation < 0) currentLocation = 0;
if (currentLocation >= (totalImages - 1)) currentLocation = (totalImages - 1);
if (newLocation === null) { // if set, we already are waiting to draw
requestAnimationFrame(setImage);
}
newLocation = currentLocation;
});
function setImage() {
if (images[newLocation]) {
ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(images[newLocation], 0, 0, 1000, 1000);
}
newLocation = null; // so the throttler knows we can draw again
}
}
images[0].onload = function() {
ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(images[currentLocation], 0, 0, 1000, 1000);
mouseWheel();
};
<canvas id="background" width="1000" height="1000"></canvas>
You can actually start make the images flip through once the viewer gets to that specific section of the page by using The Intersection Observer API
So you have to detect when your element in the the viewport, the canvas in this case.
To do this you have multiple ways.
By using Observer API
const element = document.querySelector("#background")
const Ob = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) {
// Not in the viewport
} else {
// In the viewport
// You're code here
}
});
Ob.observe(element);
Or if you want to do it in you're own.
You can use this and adapt it if needed
function elementInViewport(el) {
var top = el.offsetTop
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
}
return (
top >= window.pageYOffset &&
(top + height) <= (window.pageYOffset + window.innerHeight)
);
}
I'm trying my hands at some simple game programming in Javascript and have come to realize I need to change the way I handle sprites. The only question is, "how"?
I have a hero that moves around with the arrow keys and fires laser rays with WASD. This is how I define rays:
function Ray (x, y, width, height, direction, index) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.direction = direction;
this.index = index;
this.speed = 512;
this.disabled = false;
}
The index just indicates where in an array of rays (heh) it is being stored. I currently have a hard-coded limit of 5 simultaneous rays, although the other restrictions (screen size, ray size, speed, hero size etc) shouldn't allow for more than 4:
var rays = [];
var numberOfRays = 0;
var rayLimit = 5;
var shotClock = 300;
And so, in the update() function that gets called by the game loop, I have listeners for the WASD keys. They look like this:
// D
if (68 in keysDown && numberOfRays <= rayLimit && Date.now() - lastShootTime > shotClock) {
lastShootTime = Date.now();
var newRayIndex = findFreeRay();
rays[newRayIndex] = new Ray(hero.x + hero.width + 12, hero.y + hero.height / 2, rayImage.width, rayImage.height, 'right', newRayIndex);
numberOfRays++;
}
(findFreeRay() just returns the lowest unused or disabled (off the screen) index in rays[])
Earlier in the update() method (I have also tried putting it later) I have the logic for updating ray movement:
rays.forEach(function(ray) {
if (ray != null && !ray.disabled) {
switch(ray.direction) {
case 'right':
ray.x += ray.speed * modifier;
break;
case 'left':
ray.x -= ray.speed * modifier;
break;
case 'up':
ray.y -= ray.speed * modifier;
break;
case 'down':
ray.y += ray.speed * modifier;
break;
}
}
});
Finally, there is the image for the ray (actually, one for horizontal rays and another one for vertical rays). Currently, I am using one Image object of each globally, that the existing rays share. But I have also tried, without much luck, to create individual image objects for every ray.
// Ray images
var rayReady = false;
var rayImage = new Image();
rayImage.onload = function() {
rayReady = true;
};
rayImage.src = "images/ray.png";
var rayVertReady = false;
var rayVertImage = new Image();
rayVertImage.onload = function() {
rayVertReady = true;
};
rayVertImage.src = "images/ray_vert.png";
And here is how they get drawn:
if (rayReady && rayVertReady && numberOfRays > 0) {
rays.forEach(function(ray) {
if (ray.x > canvas.width
|| ray.x + ray.width < 0
|| ray.y > canvas.height
|| ray.y + ray.height < 0) {
numberOfRays--;
ray.disabled = true;
}
else if (ray.direction == 'right' || ray.direction == 'left'){
ctx.drawImage(rayImage, ray.x, ray.y);
}
else {
ctx.drawImage(rayVertImage, ray.x, ray.y);
}
});
}
The problem
After shooting only a few rays, new ones start to either flicker and disappear, or stay invisible altogether. They actually exist as gameplay objects though, as they can hit targets.
What likely causes this flickering?
(credit to Matt Hackett for the base of this code)
fiddle: http://jsfiddle.net/Vr3MW/
I need to rotate an image inside an canvas..I have googled and saw similar questions in stackoverflow.What i learnt is
I cannot rotate single object inside canvas.
I can rotate only thewhole canvas.
So i need to translate to center of the object and then rotate the
canvas.
I Followed exactly same stuffs , But i am struck at translating to the image center..Below is the code i am using.Here is the jsfiddle http://jsfiddle.net/J6Pfa/1/. This one is rotating the whole canvas regardless image..some one guide me where i am wrong.Thanks
//hero canvas
ball = new Hero();
var ang = 0;
herocanvas = document.createElement("canvas");
herocanvas.width = herocanvas.width = 500;
herocanvas.height = herocanvas.height = 500;
heroctx = herocanvas.getContext('2d');
document.body.appendChild(herocanvas);
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var imgSprite = new Image();
imgSprite.src = 'http://i.imgur.com/WTgOHGg.png';
imgSprite.addEventListener('load',init,false);
function init()
{
startloop();
}
function startloop()
{
heroctx.save(); //saves the state of canvas
clearherobg() ; // clear canvas
heroctx.translate(ball.drawX, ball.drawY); //let's translate
heroctx.rotate(Math.PI / 180 * (ang += 4));
ball.draw(); // draw image here
heroctx.restore();
requestAnimFrame(startloop);
}
function Hero() {
this.srcX = 0;
this.srcY = 500;
this.drawX = 220;
this.drawY = 200;
this.width = 100;
this.height = 40;
this.speed = 5;
this.isUpKey = false;
this.isRightKey = false;
this.isDownKey = false;
this.isLeftKey = false;
}
Hero.prototype.draw = function () {
heroctx.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
};
function clearherobg() {
heroctx.clearRect(0,0,500,500);
}
Those who cannot read full code ..Please check startloop() , thats the main infinite loop..ball.drawX and ball.drawY are the x and y position of image inside canvas
Hero's drawX and drawY need to be updated to new coordinate system of canvas, if u want it to be in the middle of canvas it needs to be 0,0.
Something like this: jsfiddle.net/J6Pfa/3
Hm, i dont exactly understand what you want to achieve, an image moving on the circle path ? or having image in one place, and just rotate it ?
I start on KineticJS (and on Canvas) and i'm creating a small game for learn...
Right now, I have just 2 layers :
First with a map composed by Kinetic.Image
Second with the last time who game as draw.
I want refresh display X time per second but after 20 or 30 times the game are really slow.. And it's the same when I flood event click ( who launch the draw function too)...
Moreover, i can see in the second layer : the old text are never clean, the new are added on top... :/
var stage;
var layers = {};
var CANEVAS_WIDTH = 800;
var CANEVAS_HEIGHT = 600;
var MAP_WIDTH = 10;
var MAP_HEIGHT = 10;
var MAPPING_WIDTH = 150;
var MAPPING_HEIGHT = 88;
var LEFT_X = 0;
var LEFT_Y = MAP_WIDTH*MAPPING_HEIGHT/2;
var TOP_X = MAP_WIDTH/2*MAPPING_WIDTH;
var TOP_Y = 0;
var VIEW_X = 0;
var VIEW_Y = 0;
var CURSOR_X = 6;
var CURSOR_Y = 0;
var images = {};
function loadImages(sources, callback)
{
var loadedImages = 0;
var numImages = 0;
// get num of sources
for (var src in sources)
numImages++;
for (var src in sources)
{
images[src] = new Image();
images[src].onload = function(){
if (++loadedImages >= numImages)
callback();
};
images[src].src = sources[src];
}
}
function getMouseInfo(mousePos)
{
var info = {screen_x : mousePos.x,
screen_y : mousePos.y,
mouse_x : mousePos.x+VIEW_X,
mouse_y : mousePos.y+VIEW_Y-LEFT_Y,
onMap : 0,
map_x : -1,
map_y : -1};
map_x = -(info.mouse_y - ((LEFT_Y * info.mouse_x) / TOP_X)) / MAPPING_HEIGHT;
map_y = -(-info.mouse_y - ((LEFT_Y * info.mouse_x) / TOP_X)) / MAPPING_HEIGHT;
if(map_x >= 0 && map_x < MAP_WIDTH && map_y >= 0 && map_y < MAP_HEIGHT)
{
info.map_y = parseInt(map_y);
info.map_x = parseInt(map_x);
info.onMap = 1;
}
return info;
}
function draw()
{
drawMap();
drawFPS();
stage.add(layers.mapLayer);
stage.add(layers.fpsLayer);
}
function drawFPS()
{
layers.fpsLayer.clear();
var fps = new Kinetic.Shape(function(){
var date = new Date();
var time = date.getTime();
var context = this.getContext();
context.beginPath();
context.font = "12pt Calibri";
context.fillStyle = "red";
context.fillText("FPS : "+time, 10, 20);
});
layers.fpsLayer.add(fps);
}
function drawMap()
{
var x=0,y=0;
layers.mapLayer.clear();
var s = new Kinetic.Shape(function(){
var context = this.getContext();
context.beginPath();
context.rect(0, 0, CANEVAS_WIDTH, CANEVAS_HEIGHT);
context.fillStyle = "#000";
context.fill();
context.closePath();
});
layers.mapLayer.add(s);
for(x=0; x<MAP_WIDTH; x++)
for(y=0;y<MAP_HEIGHT; y++)
{
var img = new Kinetic.Image({
image: ((x==CURSOR_X && y==CURSOR_Y)?images.testMapCursor:images.testMap)
});
img.x = x*MAPPING_WIDTH/2 + y*MAPPING_WIDTH/2 - VIEW_X;
img.y = (MAP_WIDTH-1)*MAPPING_HEIGHT/2 - x*MAPPING_HEIGHT/2 + y*MAPPING_HEIGHT/2 - VIEW_Y;
layers.mapLayer.add(img);
}
}
function changeCursorPosition(cursor_x, cursor_y)
{
CURSOR_X = cursor_x;
CURSOR_Y = cursor_y;
draw();
}
function initStage()
{
layers.mapLayer = new Kinetic.Layer();
layers.fpsLayer = new Kinetic.Layer();
draw();
}
/*
* INIT
*/
window.onload = function(){
stage = new Kinetic.Stage("container", <?=CANEVAS_WIDTH;?>, <?=CANEVAS_HEIGHT;?>);
stage.on("mousemove", function(){
var mouseInfo = getMouseInfo(stage.getMousePosition());
if(mouseInfo.onMap)
document.body.style.cursor = "pointer";
else
document.body.style.cursor = "default";
});
stage.on("mousedown", function(){
var mouseInfo = getMouseInfo(stage.getMousePosition());
if(mouseInfo.onMap)
changeCursorPosition(mouseInfo.map_x, mouseInfo.map_y);
});
var sources = {
testMap : "testMap.png",
testMapCursor : "testMapCursor.png"
};
loadImages(sources, initStage);
};
Sorry, my english are realy bad.
Thank all.
I know someone who is trying out KineticJS. I haven't used it myself, so I apologize that I cannot provide more specific help.
Unfortunately, it is very difficult to get good performance with canvas, and it depends greatly on the browser. Last I checked, Opera 12 and IE 9 performed significantly faster than other browsers, since their 2D rendering is 3D accelerated (using OpenGL and Direct3D, respectively)
I am not sure if this applies to KineticJS, but one technique you can use to improve performance with canvas is to use multiple canvas elements, and transform their positions rather than blitting on a single surface.
I've been pretty happy with the results I've gotten using Jeash, which is wired into NME's command-line tools. The development is similar to working with Flash, but it will create an HTML5 Canvas application using your code. The same application will also be able to publish to Windows, Mac, Linux, iOS, Android, webOS and Flash, as either native C++ and OpenGL, or as SWF bytecode. This gives you a lot of options for providing the best experience for each user.
http://www.haxenme.org