Migrating redraw function from D3.js v3 to D3.js v4 - html

I have a large data to plot and by doing this the browser hang so I found a solution in V3 to avoid this effect, the problem is, I need it in D3V4 or I need to brush and zoom in V3.
I'm trying to rewrite the following code in D3 V4, it seems as if it cracks by updateSelection. Did I miss something?
my code:
<html>
<head>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var height = 500;
var width = 960;
var timer, startTime;
var startTime;
var BATCH_SIZE = 1000;
function showTimeSince(startTime) {
var currentTime = new Date().getTime();
var runtime = currentTime - startTime;
document.getElementById('timeRendering').innerHTML = runtime + 'ms';
}
function startTimer() {
stopTimer();
startTime = new Date().getTime();
timer = setInterval(function() {
showTimeSince(startTime);
}, 10);
showTimeSince(startTime);
}
function stopTimer() {
if (timer) {
clearInterval(timer);
}
showTimeSince(startTime);
}
function drawCircles(svg, data, batchSize) {
startTimer();
var circles = svg.selectAll('circle').data(data);
function drawBatch(batchNumber) {
return function() {
var startIndex = batchNumber * batchSize;
var stopIndex = Math.min(data.length, startIndex + batchSize);
var updateSelection = d3.selectAll(circles[0].slice(startIndex, stopIndex));
var enterSelection = d3.selectAll(circles.enter()[0].slice(startIndex, stopIndex));
var exitSelection = d3.selectAll(circles.exit()[0].slice(startIndex, stopIndex));
enterSelection.each(function(d, i) {
var newElement = svg.append('circle')[0][0];
enterSelection[0][i] = newElement;
updateSelection[0][i] = newElement;
newElement.__data__ = this.__data__;
}).attr('r', 3);
exitSelection.remove();
updateSelection
.attr('cx', function(d) { return d.x })
.attr('cy', function(d) { return d.y });
if (stopIndex >= data.length) {
stopTimer();
} else {
setTimeout(drawBatch(batchNumber + 1), 0);
}
};
}
setTimeout(drawBatch(0), 0);
}
function renderChart() {
var numPoints = parseInt(document.getElementsByName('numPoints')[0].value, 10);
if (isNaN(numPoints)) {
return;
}
startTimer();
var data = [];
for (var i = 0; i < numPoints; i++) {
data.push({
x: Math.random() * width,
y: Math.random() * height
});
}
var svg = d3.selectAll('svg').data([0]);
svg.enter().append('svg')
.attr("height", height)
.attr("width", width);
drawCircles(svg, data, BATCH_SIZE);
}
</script>
</head>
<body>
<form action="">
<input name="numPoints" type="text" value="10000">
<button type="button" id="render" onClick="renderChart()">Render</button>
</form>
Time Rendering: <span id="timeRendering"></span>
</body>
</html>

Related

mouse background image with canvas in html5

I want something like this site , look at mouse background in header section:
Link
when i check page source i found this:
<canvas id="header-canvas" width="1360" height="676"></canvas>
Take a look at source code and identify which JS plugins are being used.
I have pulled it apart and found its using green sock https://greensock.com
Take a look at http://codepen.io/elliottgg/pen/YpQBpZ
Scroll down to line 40 to see where the magic is happening
(function() {
var width, height, largeHeader, canvas, ctx, points, target, animateHeader = true;
// Main
initHeader();
initAnimation();
addListeners();
function initHeader() {
width = window.innerWidth;
height = window.innerHeight;
target = {x: width/2, y: height/2};
largeHeader = document.getElementById('header');
largeHeader.style.height = height+'px';
canvas = document.getElementById('header-canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
// create points
points = [];
for(var x = 0; x < width; x = x + width/20) {
for(var y = 0; y < height; y = y + height/20) {
var px = x + Math.random()*width/20;
var py = y + Math.random()*height/20;
var p = {x: px, originX: px, y: py, originY: py };
points.push(p);
}
}
// for each point find the 5 closest points
for(var i = 0; i < points.length; i++) {
var closest = [];
var p1 = points[i];
for(var j = 0; j < points.length; j++) {
var p2 = points[j]
if(!(p1 == p2)) {
var placed = false;
for(var k = 0; k < 5; k++) {
if(!placed) {
if(closest[k] == undefined) {
closest[k] = p2;
placed = true;
}
}
}
for(var k = 0; k < 5; k++) {
if(!placed) {
if(getDistance(p1, p2) < getDistance(p1, closest[k])) {
closest[k] = p2;
placed = true;
}
}
}
}
}
p1.closest = closest;
}
// assign a circle to each point
for(var i in points) {
var c = new Circle(points[i], 2+Math.random()*2, 'rgba(255,255,255,0.8)');
points[i].circle = c;
}
}
// Event handling
function addListeners() {
if(!('ontouchstart' in window)) {
window.addEventListener('mousemove', mouseMove);
}
window.addEventListener('scroll', scrollCheck);
window.addEventListener('resize', resize);
}
function mouseMove(e) {
var posx = posy = 0;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
target.x = posx;
target.y = posy;
}
function scrollCheck() {
if(document.body.scrollTop > height) animateHeader = false;
else animateHeader = true;
}
function resize() {
width = window.innerWidth;
height = window.innerHeight;
largeHeader.style.height = height+'px';
canvas.width = width;
canvas.height = height;
}
// animation
function initAnimation() {
animate();
for(var i in points) {
shiftPoint(points[i]);
}
}
function animate() {
if(animateHeader) {
ctx.clearRect(0,0,width,height);
for(var i in points) {
// detect points in range
if(Math.abs(getDistance(target, points[i])) < 4000) {
points[i].active = 0.3;
points[i].circle.active = 0.6;
} else if(Math.abs(getDistance(target, points[i])) < 20000) {
points[i].active = 0.1;
points[i].circle.active = 0.3;
} else if(Math.abs(getDistance(target, points[i])) < 40000) {
points[i].active = 0.02;
points[i].circle.active = 0.1;
} else {
points[i].active = 0.0;
points[i].circle.active = 0.0;
}
drawLines(points[i]);
points[i].circle.draw();
}
}
requestAnimationFrame(animate);
}
function shiftPoint(p) {
TweenLite.to(p, 1+1*Math.random(), {x:p.originX-50+Math.random()*100,
y: p.originY-50+Math.random()*100, ease:Circ.easeInOut,
onComplete: function() {
shiftPoint(p);
}});
}
// Canvas manipulation
function drawLines(p) {
if(!p.active) return;
for(var i in p.closest) {
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.closest[i].x, p.closest[i].y);
ctx.strokeStyle = 'rgba(255,255,255,'+ p.active+')';
ctx.stroke();
}
}
function Circle(pos,rad,color) {
var _this = this;
// constructor
(function() {
_this.pos = pos || null;
_this.radius = rad || null;
_this.color = color || null;
})();
this.draw = function() {
if(!_this.active) return;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'rgba(255,255,255,'+ _this.active+')';
ctx.fill();
};
}
// Util
function getDistance(p1, p2) {
return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
}

Google Maps API v3 - Draggable Marker Along a Polyline

I am trying to create a draggable marker that is confined to a polyline. I have read this post (Confine dragging of Google Maps V3 Marker to Polyline), but I do not want to create the points that the marker can move along. Are there other ways to do this without having to create a points array for the marker? If anyone can point me in the right direction, it is much appreciated.
From what I understand, you have to load the polyline points into an array. It seems that there is no way around this. I am not sure how the the directions api snaps to roads, but I am assuming that it is based on this concept (loading points into an array).
I have found an older maps v2 library that updates the marker based on mouse movement events, which loads the line data on zoom end. I have updated the code to work with api v3 and replaced the mouse events with drag events.
To use this library, initialize like this:
var snapToRoute = new SnapToRoute(map_instance, initial_marker, polyline);
The library can be found here: SnapToRoute
** Update ** example fiddle
Here is my modified version:
function SnapToRoute(map, marker, polyline) {
this.routePixels_ = [];
this.normalProj_ = map.getProjection();
this.map_ = map;
this.marker_ = marker;
this.polyline_ = polyline;
this.init_();
}
SnapToRoute.prototype.init_ = function () {
this.loadLineData_();
this.loadMapListener_();
};
SnapToRoute.prototype.updateTargets = function (marker, polyline) {
this.marker_ = marker || this.marker_;
this.polyline_ = polyline || this.polyline_;
this.loadLineData_();
};
SnapToRoute.prototype.loadMapListener_ = function () {
var me = this;
google.maps.event.addListener(me.marker_, "dragend", function (evt) {
me.updateMarkerLocation_(evt.latLng);
});
google.maps.event.addListener(me.marker_, "drag", function (evt) {
me.updateMarkerLocation_(evt.latLng);
});
google.maps.event.addListener(me.map_, "zoomend", function (evt) {
me.loadLineData_();
});
};
SnapToRoute.prototype.loadLineData_ = function () {
var zoom = this.map_.getZoom();
this.routePixels_ = [];
var path = this.polyline_.getPath();
for (var i = 0; i < path.getLength() ; i++) {
var Px = this.normalProj_.fromLatLngToPoint(path.getAt(i));
this.routePixels_.push(Px);
}
};
SnapToRoute.prototype.updateMarkerLocation_ = function (mouseLatLng) {
var markerLatLng = this.getClosestLatLng(mouseLatLng);
this.marker_.setPosition(markerLatLng);
};
SnapToRoute.prototype.getClosestLatLng = function (latlng) {
var r = this.distanceToLines_(latlng);
return this.normalProj_.fromPointToLatLng(new google.maps.Point(r.x, r.y));
};
SnapToRoute.prototype.getDistAlongRoute = function (latlng) {
if (typeof (opt_latlng) === 'undefined') {
latlng = this.marker_.getLatLng();
}
var r = this.distanceToLines_(latlng);
return this.getDistToLine_(r.i, r.to);
};
SnapToRoute.prototype.distanceToLines_ = function (mouseLatLng) {
var zoom = this.map_.getZoom();
var mousePx = this.normalProj_.fromLatLngToPoint(mouseLatLng);
var routePixels_ = this.routePixels_;
return this.getClosestPointOnLines_(mousePx, routePixels_);
};
SnapToRoute.prototype.getDistToLine_ = function (line, to) {
var routeOverlay = this.polyline_;
var d = 0;
for (var n = 1; n < line; n++) {
d += google.maps.geometry.spherical.computeDistanceBetween(routeOverlay.getAt(n - 1), routeOverlay.getAt(n));
}
d += google.maps.geometry.spherical.computeDistanceBetween(routeOverlay.getAt(line - 1), routeOverlay.getAt(line)) * to;
return d;
};
SnapToRoute.prototype.getClosestPointOnLines_ = function (pXy, aXys) {
var minDist;
var to;
var from;
var x;
var y;
var i;
var dist;
if (aXys.length > 1) {
for (var n = 1; n < aXys.length ; n++) {
if (aXys[n].x !== aXys[n - 1].x) {
var a = (aXys[n].y - aXys[n - 1].y) / (aXys[n].x - aXys[n - 1].x);
var b = aXys[n].y - a * aXys[n].x;
dist = Math.abs(a * pXy.x + b - pXy.y) / Math.sqrt(a * a + 1);
} else {
dist = Math.abs(pXy.x - aXys[n].x);
}
var rl2 = Math.pow(aXys[n].y - aXys[n - 1].y, 2) + Math.pow(aXys[n].x - aXys[n - 1].x, 2);
var ln2 = Math.pow(aXys[n].y - pXy.y, 2) + Math.pow(aXys[n].x - pXy.x, 2);
var lnm12 = Math.pow(aXys[n - 1].y - pXy.y, 2) + Math.pow(aXys[n - 1].x - pXy.x, 2);
var dist2 = Math.pow(dist, 2);
var calcrl2 = ln2 - dist2 + lnm12 - dist2;
if (calcrl2 > rl2) {
dist = Math.sqrt(Math.min(ln2, lnm12));
}
if ((minDist == null) || (minDist > dist)) {
to = Math.sqrt(lnm12 - dist2) / Math.sqrt(rl2);
from = Math.sqrt(ln2 - dist2) / Math.sqrt(rl2);
minDist = dist;
i = n;
}
}
if (to > 1) {
to = 1;
}
if (from > 1) {
to = 0;
from = 1;
}
var dx = aXys[i - 1].x - aXys[i].x;
var dy = aXys[i - 1].y - aXys[i].y;
x = aXys[i - 1].x - (dx * to);
y = aXys[i - 1].y - (dy * to);
}
return { 'x': x, 'y': y, 'i': i, 'to': to, 'from': from };
};
example fiddle
code snippet:
var geocoder;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
var marker;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
calcRoute("New York, NY", "Baltimore, MD");
directionsDisplay.setMap(map);
}
google.maps.event.addDomListener(window, "load", initialize);
function calcRoute(start, end) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// directionsDisplay.setDirections(response);
renderRoute(response);
}
});
}
function renderRoute(response) {
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
var detailsPanel = document.getElementById("direction_details");
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
if (i == 0) {
marker = new google.maps.Marker({
position: legs[i].start_location,
draggable: true,
map: map
});
}
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
var snapToRoute = new SnapToRoute(map, marker, polyline);
}
function SnapToRoute(map, marker, polyline) {
this.routePixels_ = [];
this.normalProj_ = map.getProjection();
this.map_ = map;
this.marker_ = marker;
this.editable_ = Boolean(false);
this.polyline_ = polyline;
this.init_();
}
SnapToRoute.prototype.init_ = function() {
this.loadLineData_();
this.loadMapListener_();
};
SnapToRoute.prototype.updateTargets = function(marker, polyline) {
this.marker_ = marker || this.marker_;
this.polyline_ = polyline || this.polyline_;
this.loadLineData_();
};
SnapToRoute.prototype.loadMapListener_ = function() {
var me = this;
google.maps.event.addListener(me.marker_, "dragend", function(evt) {
me.updateMarkerLocation_(evt.latLng);
});
google.maps.event.addListener(me.marker_, "drag", function(evt) {
me.updateMarkerLocation_(evt.latLng);
});
google.maps.event.addListener(me.map_, "zoomend", function(evt) {
me.loadLineData_();
});
};
SnapToRoute.prototype.loadLineData_ = function() {
var zoom = this.map_.getZoom();
this.routePixels_ = [];
var path = this.polyline_.getPath();
for (var i = 0; i < path.getLength(); i++) {
var Px = this.normalProj_.fromLatLngToPoint(path.getAt(i));
this.routePixels_.push(Px);
}
};
SnapToRoute.prototype.updateMarkerLocation_ = function(mouseLatLng) {
var markerLatLng = this.getClosestLatLng(mouseLatLng);
this.marker_.setPosition(markerLatLng);
};
SnapToRoute.prototype.getClosestLatLng = function(latlng) {
var r = this.distanceToLines_(latlng);
return this.normalProj_.fromPointToLatLng(new google.maps.Point(r.x, r.y));
};
SnapToRoute.prototype.getDistAlongRoute = function(latlng) {
if (typeof(opt_latlng) === 'undefined') {
latlng = this.marker_.getLatLng();
}
var r = this.distanceToLines_(latlng);
return this.getDistToLine_(r.i, r.to);
};
SnapToRoute.prototype.distanceToLines_ = function(mouseLatLng) {
var zoom = this.map_.getZoom();
var mousePx = this.normalProj_.fromLatLngToPoint(mouseLatLng);
var routePixels_ = this.routePixels_;
return this.getClosestPointOnLines_(mousePx, routePixels_);
};
SnapToRoute.prototype.getDistToLine_ = function(line, to) {
var routeOverlay = this.polyline_;
var d = 0;
for (var n = 1; n < line; n++) {
d += google.maps.geometry.spherical.computeDistanceBetween(routeOverlay.getAt(n - 1), routeOverlay.getAt(n));
}
d += google.maps.geometry.spherical.computeDistanceBetween(routeOverlay.getAt(line - 1), routeOverlay.getAt(line)) * to;
return d;
};
SnapToRoute.prototype.getClosestPointOnLines_ = function(pXy, aXys) {
var minDist;
var to;
var from;
var x;
var y;
var i;
var dist;
if (aXys.length > 1) {
for (var n = 1; n < aXys.length; n++) {
if (aXys[n].x !== aXys[n - 1].x) {
var a = (aXys[n].y - aXys[n - 1].y) / (aXys[n].x - aXys[n - 1].x);
var b = aXys[n].y - a * aXys[n].x;
dist = Math.abs(a * pXy.x + b - pXy.y) / Math.sqrt(a * a + 1);
} else {
dist = Math.abs(pXy.x - aXys[n].x);
}
var rl2 = Math.pow(aXys[n].y - aXys[n - 1].y, 2) + Math.pow(aXys[n].x - aXys[n - 1].x, 2);
var ln2 = Math.pow(aXys[n].y - pXy.y, 2) + Math.pow(aXys[n].x - pXy.x, 2);
var lnm12 = Math.pow(aXys[n - 1].y - pXy.y, 2) + Math.pow(aXys[n - 1].x - pXy.x, 2);
var dist2 = Math.pow(dist, 2);
var calcrl2 = ln2 - dist2 + lnm12 - dist2;
if (calcrl2 > rl2) {
dist = Math.sqrt(Math.min(ln2, lnm12));
}
if ((minDist == null) || (minDist > dist)) {
to = Math.sqrt(lnm12 - dist2) / Math.sqrt(rl2);
from = Math.sqrt(ln2 - dist2) / Math.sqrt(rl2);
minDist = dist;
i = n;
}
}
if (to > 1) {
to = 1;
}
if (from > 1) {
to = 0;
from = 1;
}
var dx = aXys[i - 1].x - aXys[i].x;
var dy = aXys[i - 1].y - aXys[i].y;
x = aXys[i - 1].x - (dx * to);
y = aXys[i - 1].y - (dy * to);
}
return {
'x': x,
'y': y,
'i': i,
'to': to,
'from': from
};
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

Three.js collision detection (ERROR)

Im trying to make a collision detection "program" in Three.js (WEBGL library).
However, Im getting an error "cannot call method multiplyvector3 of undefined".
Can anyone tell me what Im doing wrong?
The function for collision detection I just implemented, is:
function animate() {
requestAnimationFrame(animate);
render();
for (var vertexIndex = 0; geometries[0].vertices.length; vertexIndex++)
{
var localVertex = geometries[0].vertices[vertexIndex].clone();
var globalVertex = geometries[0].matrix.multiplyVector3(localVertex);
var directionVector = globalVertex.subSelf(meshes[5].position);
var ray = new THREE.Ray( meshes[5].position, directionVector.clone().normalize() );
var collisionResults = ray.intersectObjects( meshes);
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )
{
}
else {
meshes[5].position.y -= 0.15;
meshes[5].rotation.z -= 0.15;
}
}
}
And the full code is,
<html>
<head>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/three.js/r54/three.min.js'></script>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var camera, scene, renderer, material;
var meshes = new Array();
var geometries = new Array();
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 500;
camera.position.x += 125;
scene.add(camera);
geometries[0] = new THREE.CubeGeometry(35, 35, 35);
material = new THREE.MeshNormalMaterial();
geometries[1] = new THREE.SphereGeometry(35, 35, 35);
material = new THREE.MeshNormalMaterial();
for(var i = 0; i < 5; i++) {
meshes[i] = new THREE.Mesh(geometries[0], material);
}
meshes[5] = new THREE.Mesh(geometries[1], material);
for(var i = 0; i < 5; i++) {
meshes[i].position.x = (35*i);
meshes[i].rotation.x = 5;
}
meshes[5].position.y = (100);
for(var i = 0; i < 5; i++) {
scene.add(meshes[i]);
}
scene.add(meshes[5]);
renderer = new THREE.CanvasRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
document.addEventListener("mousemove", onDocumentMouseMove, false);
}
function onDocumentMouseMove(event) {
}
function animate() {
requestAnimationFrame(animate);
render();
for (var vertexIndex = 0; geometries[0].vertices.length; vertexIndex++)
{
var localVertex = geometries[0].vertices[vertexIndex].clone();
var globalVertex = geometries[0].matrix.multiplyVector3(localVertex);
var directionVector = globalVertex.subSelf(meshes[5].position);
var ray = new THREE.Ray( meshes[5].position, directionVector.clone().normalize() );
var collisionResults = ray.intersectObjects( meshes);
if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() )
{
}
else {
meshes[5].position.y -= 0.15;
meshes[5].rotation.z -= 0.15;
}
}
}
function render() {
renderer.render(scene, camera);
}
}//]]>
</script>
</head>
<body>
</body>
</html>
Thank you!
for (var vertexIndex = 0; geometries[0].vertices.length; vertexIndex++)
should be
for (var vertexIndex = 0; vertexIndex < geometries[0].vertices.length; vertexIndex++)

HTML5, Easel.js game problems

Been working on an easel game tutorial that involves an animated character going across the screen and avoiding crates falling from above. I've followed the code in the tutorial exactly but no joy;nothing seems to be loading (including images which are mapped correctly). No errors regarding syntax seem to occur so not sure what the problem is. It's a fair bit of code so totally understand if no-one has the time but just in case here it is ;
Site Page code (ill post the individual JavaScript file codes if anyone is interested;
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: #000;
}
</style>
<script src="lib/easeljs-0.6.0.min.js"></script>
<script src="JS/Platform.js"></script>
<script src="JS/Hero.js"></script>
<script src="JS/Crate.js"></script>
<script>
var KEYCODE_SPACE = 32, KEYCODE_LEFT = 37, KEYCODE_RIGHT = 39;
var canvas, stage, lfheld, rtheld, platforms, crates, hero, heroCenter, key, door, gameTxt;
var keyDn = false, play=true, dir="right";
var loaded = 0, vy = 0, vx = 0;
var jumping = false, inAir = true, gravity = 2;
var img = new Image();
var bgimg = new Image();
var kimg = new Image();
var dimg = new Image();
var platformW = [300, 100, 180, 260, 260, 100, 100];
var platformX = [40, 220, 320, 580, 700, 760, 760];
var platformY = [460, 380, 300, 250, 550, 350, 450];
document.onkeydown=handleKeyDown;
document.onkeyup=handleKeyUp;
function init(){
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
bgimg.onload = this.handleImageLoad;
bgimg.src = "img/scene.jpg";
kimg.onload = this.handleImageLoad;
kimg.src="img/key.png";
dimg.onload = this.handleImageLoad;
dimg.src = "img/door.jpg";
img.onload = this.handleImageLoad;
img.src = "img/hero.png";
}
function handleImageLoad(event) {
loaded+=1;
if (loaded==4){
start();
}
}
function handleKeyDown(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = true;
dir="left"; break;
case KEYCODE_RIGHT: rtHeld = true;
dir="right"; break;
case KEYCODE_SPACE: jump(); break;
}
}
function handleKeyUp(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = false;
keyDn=false; hero.gotoAndStop("idle_h"); break;
case KEYCODE_RIGHT: rtHeld = false;
keyDn=false; hero.gotoAndStop("idle"); break;
}
}
function start(){
var bg = new createjs.Bitmap(bgimg);
stage.addChild(bg);
door = new createjs.Bitmap(dimg);
door.x = 131;
door.y = 384;
stage.addChild(door);
hero = new Hero(img);
hero.x = 80;
hero.y = 450;
stage.addChild(Hero);
crates = new Array();
paltforms = new Array();
for(i=0; i < platformW.length; i++){
var platform = new Platform(platformW[i],20);
platforms.push(platform);
stage.addChild(platform);
platform.x = platformX[i];
platform.y = platformY[i];
}
for(j=0; j < 5; j++){
var crate = new Crate();
crates.push(crate);
stage.addChild(crate);
resetCrates(crate);
}
key = new createjs.Bitmap(kimg);
key.x = 900;
key.y = 490;
stage.addChild(key);
Ticker.setFPS(30);
Ticker.addListener(window);
stage.update();
}
function tick() {
heroCenter = hero.y-40;
if (play){
vy+=gravity;
if (inAir){
hero.y+=vy;
}
if (vy>15){
vy=15;
}
for(i=0; i < platforms.length; i++){
if (hero.y >= platforms[i].y && hero.y<=(platforms[i].y+platforms[i].height) && hero.x>
platforms[i].x && hero.x<(platforms[i].
x+platforms[i].width)){;
hero.y=platforms[i].y;
vy=0;
jumping = false;
inAir = false;
break;
}else{
inAir = true;
}
}
for(j=0; j < crates.length; j++){
var ct = crates[j];
ct.y+=ct.speed;
ct.rotation+=3;
if (ct.y>650){
resetCrates(ct);
}
if (collisionHero (ct.x, ct.y, 20)){
gameOver();}
}
if (collisionHero (key.x+20, key.y+20,
20)){
key.visible=false;
door.visible=false;
}
if (collisionHero (door.x+20, door.y+40,
20) && key.visible==false){nextLevel();}
if (lfHeld){vx = -5;}
if (rtHeld){vx = 5;}
if(lfHeld && keyDn==false && inAir==false)
{
hero.gotoAndPlay("walk_h");
keyDn=true;
}
if(rtHeld && keyDn==false &&
inAir==false){
hero.gotoAndPlay("walk");
keyDn=true;
}
if (dir=="left" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle_h");
}
if (dir=="right" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle");
}
hero.x+=vx;
vx=vx*0.5;
if (hero.y>610){
gameOver();
}
}
stage.update();
}
function end(){
play=false;
var l = crates.length;
for (var i=0; i<l; i++){
var c = crates[i];
resetCrates(c);
}
hero.visible=false;
stage.update();
}
function nextLevel(){
gameTxt = new createjs.Text("Well Done\n\n",
"36px Arial", "#000");
gameTxt.text += "Prepare for Level 2";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
}
function gameOver(){
gameTxt = new createjs.Text("Game Over\n\n",
"36px Arial", "#000");
gameTxt.text += "Click to Play Again.";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
canvas.onclick = handleClick;
}
function handleClick() {
canvas.onclick = null;
hero.visible=true;
hero.x = 80;
hero.y = 450;
door.visible=true;
key.visible=true;
stage.removeChild(gameTxt);
play=true;
}
function collisionHero (xPos, yPos,
Radius){
var distX = xPos - hero.x;
var distY = yPos - heroCenter;
var distR = Radius + 20;
if (distX * distX + distY * distY <=
distR * distR){
return true;
}
}
function jump(){
if (jumping == false && inAir == false){
if (dir=="right"){
hero.gotoAndStop("jump");
}else{
hero.gotoAndStop("jump_h");
}
hero.y -=20;
vy = -25;
jumping = true;
keyDn=false;
}
}
function resetCrates(crt) {
crt.x = canvas.width * Math.random()|0;
crt.y = 0 - Math.random()*500;
crt.speed = (Math.random()*5)+8;
}
</script>
<title>Game</title>
</head>
<body onload="init();">
<canvas id="canvas" width="960px" height="600px"></canvas>
</body>
</html>
Adding the js files as listed in the header.
Platform.js:
(function(window) {
function Platform(w,h) {
this.width = w;
this.height = h;
this.initialize();
}
Platform.prototype = new createjs.Container ();
Platform.prototype.platformBody = null;
Platform.prototype.Container_initialize = Platform.prototype.initialize;
Platform.prototype.initialize = function() {
this.Container_initialize();
this.platformBody = new createjs.Shape();
this.addChild(this.platformBody);
this.makeShape();
}
Platform.prototype.makeShape = function() {
var g = this.platformBody.graphics;
g.drawRect(0,0,this.width,this.height);
}
window.Platform = Platform;
}(window));
Hero.js
(function(window) {
function Hero(imgHero) {
this.initialize(imgHero);
}
Hero.prototype = new createjs.BitmapAnimation();
Hero.prototype.Animation_initialize = Hero.prototype.initialize;
Hero.prototype.initialize = function(imgHero) {
var spriteSheet = new createjs.SpriteSheet({
images: [imgHero],
frames: {width: 60, height: 85, regX: 29, regY: 80}, animations: {
walk: [0, 19, "walk"],
idle: [20, 20],
jump: [21, 21] } });
SpriteSheetUtils
.addFlippedFrames(spriteSheet, true, false,
false);
this.Animation_initialize(spriteSheet);
this.gotoAndStop("idle");
}
window.Hero = Hero;
}(window));
Crate.js
(function(window) {
function Crate() {
this.initialize();
}
Crate.prototype = new createjs.Container();
Crate.prototype.img = new Image();
Crate.prototype.Container_initialize =
Crate.prototype.initialize;
Crate.prototype.initialize = function() {
this.Container_initialize();
var bmp = new createjs.Bitmap("img/crate.jpg");
bmp.x=-20;
bmp.y=-20;
this.addChild(bmp);}
window.Crate = Crate;
}(window));
I noticed that you try to initialize the EaselJS-objects without a namespace:
stage = new Stage(canvas);
But since 0.5.0 you have to use the createjs-namespace(or map the namespace to window before you do anything)
So what you would have to do now will ALL easelJS-classes is to add a createjs. before them when you are creating a new instance like this:
stage = new createjs.Stage(canvas);
Not sure if that's everything, but it's a start, hope this helps.
You can read more on CreateJS namepsacing here: https://github.com/CreateJS/EaselJS/blob/master/README_CREATEJS_NAMESPACE.txt

Requestanimationframe usage issue

I got the following RequestAnimationframe function from http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
I am trying to use it. But not sure how to call it and use it. Can someone give me a simple example. I am new to this html5 animation thing so you can understand..
I will really appreciate any help! The function is below..
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelRequestAnimationFrame = window[vendors[x]+
'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}())
Just paste that code into your JS or in its own file and put this inside of your rendering function at the very bottom.
requestAnimationFrame(yourrenderingfunction);
Live Demo
// requestAnimationFrame shim
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelRequestAnimationFrame = window[vendors[x]+
'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}())
// Sprite unimportant, just for example purpose
function Sprite(){
this.x = 0;
this.y = 50;
}
Sprite.prototype.draw = function(){
ctx.fillStyle = "rgb(255,0,0)";
ctx.fillRect(this.x, this.y, 10, 10);
}
// setup
var canvas = document.getElementsByTagName("canvas")[0],
ctx = canvas.getContext("2d");
canvas.width = 200;
canvas.height = 200;
//init the sprite
var sprite = new Sprite();
// draw the sprite and update it using request animation frame.
function update(){
ctx.clearRect(0,0,200,200);
sprite.x+=0.5;
if(sprite.x>200){
sprite.x = 0;
}
sprite.draw();
// makes it update everytime
requestAnimationFrame(update);
}
// initially calls the update function to get it started
update();