Trying to get series values in the selected area after mouseup.
Need to calculate width and height of the selected are in the chart with respect to axis.
[`https://jsbin.com/wapovohiwe/edit?html,output`][1]
I modified your example to draw the rectangle and to output the coordinates of the
Chart1 = new Tee.Chart("canvas");
Chart1.legend.visible = false;
Chart1.panel.format.gradient.visible = false;
Chart1.panel.format.fill = "white";
Chart1.walls.back.format.fill = "white";
Chart1.addSeries(new Tee.Line([1, 3, 0, 2, 7, 5, 6]));
Chart1.zoom.enabled = false;
var myFormat = new Tee.Format(Chart1);
myFormat.transparency = 0.9;
var rect = {},
drag = false;
Chart1.mousedown = function(e) {
rect.startX = e.x - canvas.offsetLeft - canvas.parentElement.offsetLeft - canvas.parentElement.parentElement.offsetLeft;
rect.startY = e.y - canvas.offsetTop - canvas.parentElement.offsetTop - canvas.parentElement.parentElement.offsetTop;
drag = true;
}
Chart1.mouseup = function(p) {
var i, tmpP = {};
points = [];
var s = Chart1.series.items[0];
for (i = 0; i < s.count(); i++) {
s.calc(i, tmpP);
if ((tmpP.x >= rect.startX) && (tmpP.x <= rect.startX + rect.w) && (tmpP.y >= rect.startY) && (tmpP.y <= rect.startY + rect.h))
console.log("index: " + i + ", value: " + s.data.values[i]);
}
drag = false;
}
Chart1.mousemove = function(e) {
if (drag) {
rect.w = e.x - rect.startX;
rect.h = e.y - rect.startY;
drawChart();
}
}
function drawChart() {
Chart1.draw();
myFormat.rectangle(rect.startX, rect.startY, rect.w, rect.h);
}
Chart1.draw();
<script src="https://www.steema.com/files/public/teechart/html5/latest/src/teechart.js"></script>
<canvas id="canvas" height="400" width="700"></canvas>
Related
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>
I want to drag and drop multiple images from one canvas to another using HTML5. The tutorial that I found by googling shows how to drag and drop only one image.
Below is the code that I tried. In that I am not able to add multiple images. I am able to drag and drop one image one but not able to add many image to that canvas.
<script>
window.onload = function ()
{
var canvas1 = document.getElementById("cvs1");
var canvas2 = document.getElementById("cvs2");
var context1 = canvas1.getContext('2d');
var context2 = canvas2.getContext('2d');
var imageXY = {x: 5, y: 5};
/**
* This draws the image to the canvas
*/
function Draw ()
{
//Clear both canvas first
context1.clearRect(0,0,canvas1.width,canvas1.height);
context2.clearRect(0,0,canvas2.width,canvas2.height);
//Draw a red rectangle around the image
if (state && state.dragging) {
state.canvas.getContext('2d').strokeStyle = 'red';
state.canvas.getContext('2d').strokeRect(imageXY.x - 2.5,
imageXY.y - 2.5,
state.image.width + 5,
state.image.height + 5);
}
// Now draw the image
state.canvas.getContext('2d').drawImage(state.image, imageXY.x, imageXY.y);
}
canvas2.onclick =
canvas1.onclick = function (e)
{
if (state && state.dragging) {
state.dragging = false;
Draw();
return;
}
var mouseXY = RGraph.getMouseXY(e);
state.canvas = e.target;
if ( mouseXY[0] > imageXY.x
&& mouseXY[0] < (imageXY.x + state.image.width)
&& mouseXY[1] > imageXY.y
&& mouseXY[1] < (imageXY.y + state.image.height)) {
state.dragging = true;
state.originalMouseX = mouseXY[0];
state.originalMouseY = mouseXY[1];
state.offsetX = mouseXY[0] - imageXY.x;
state.offsetY = mouseXY[1] - imageXY.y;
}
}
canvas1.onmousemove =
canvas2.onmousemove = function (e)
{
if (state.dragging) {
state.canvas = e.target;
var mouseXY = RGraph.getMouseXY(e);
// Work how far the mouse has moved since the mousedon event was triggered
var diffX = mouseXY[0] - state.originalMouseX;
var diffY = mouseXY[1] - state.originalMouseY;
imageXY.x = state.originalMouseX + diffX - state.offsetX;
imageXY.y = state.originalMouseY + diffY - state.offsetY;
Draw();
e.stopPropagation();
}
}
/**
* Load the image on canvas1 initially and set the state up with some defaults
*/
state = {}
state.dragging = false;
state.canvas = document.getElementById("cvs1");
state.image = new Image();
state.image.src = 'images/logo.png';
state.offsetX = 0;
state.offsetY = 0;
state.image.onload = function ()
{
Draw();
}
}
</script>
<canvas id="cvs1" width="400" height="125" style="float: left">[No canvas support]</canvas>
<canvas id="cvs2" width="400" height="125" style="float: left; margin-left: 100px">[No canvas support]</canvas>
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
I have a flash project that loads an image and applies a grey saturation over it. There is a button beneath the image that when highlighted or the mouse hovers over it removes the saturation and restores the original color to the image. This works fine in demo mode and in the stand-alone flash player, but when I try to use it online (HTML) page the hover of feature no longer restores the color to the image. My code is below, I hope someone smarter than me know's what the problem is.
Thanks.
function parsXML()
{
mainGalleryNode = gallery_xml.childNodes[0].childNodes;
path = mainGalleryNode[_root.gallerySel - 1].attributes.path;
lenGall = mainGalleryNode[_root.gallerySel - 1].childNodes.length;
lenCat = mainGalleryNode.length;
for (var _loc2 = 0; _loc2 < lenGall; ++_loc2)
{
arrayImage[_loc2] = path + mainGalleryNode[_root.gallerySel - 1].childNodes[_loc2].attributes.pic;
arrayThumb[_loc2] = path + mainGalleryNode[_root.gallerySel - 1].childNodes[_loc2].attributes.thumbnail;
arrayTitle[_loc2] = mainGalleryNode[_root.gallerySel - 1].childNodes[_loc2].attributes.name;
arrayDescription[_loc2] = mainGalleryNode[_root.gallerySel - 1].childNodes[_loc2].attributes.description;
} // end of for
} // End of the function
function arrayThumbs()
{
for (var _loc3 = 1; _loc3 <= lenGall; ++_loc3)
{
_thumbs._thumbs.attachMovie("thumb", "thumb" + _loc3, _loc3);
var _loc2 = _thumbs._thumbs["thumb" + _loc3];
_loc2.index = _loc3;
_loc2._y = Math.floor(_loc2._height + 1) * (_loc3 - 1);
_loc2._mc._txt.text = _loc2.index;
_loc2.onRollOver = function ()
{
this.gotoAndPlay("over");
};
_loc2.onRollOut = _loc2.onReleaseOutside = function ()
{
this.gotoAndPlay("out");
};
_loc2.onRelease = function ()
{
caurina.transitions.Tweener.addTween(_mc1._mc, {_saturation: 1, time: 5.000000E-001});
mcLoader.loadClip(arrayImage[this.index - 1], _mc1._mc);
currentIndex = this.index - 1;
getDes();
};
} // end of for
counter = 1;
} // End of the function
function menuCat()
{
for (var _loc4 = 1; _loc4 <= lenCat; ++_loc4)
{
_category.attachMovie("btnCat", "btnCat" + _loc4, _loc4);
var _loc3 = _category["btnCat" + _loc4];
var _loc6 = _category["btnCat" + (_loc4 - 1)];
_loc3.index = _loc4;
arrayNameGall[_loc4 - 1] = mainGalleryNode[_loc4 - 1].attributes.name;
_loc3._mc._txt.autoSize = true;
_category["btnCat" + _loc4]._mc._txt.text = arrayNameGall[_loc4 - 1];
_loc3._red._width = _loc3._mc._txt.textWidth + 10;
_loc3._red._x = _loc3._mc._txt.textWidth / 2;
_loc3._mask._width = _loc3._mc._txt.textWidth + 10;
_loc3._mask._x = _loc3._mc._txt.textWidth / 2;
for (var _loc5 = 1; _loc5 <= 3; ++_loc5)
{
_loc3["_arr" + _loc5]._x = _loc3._mc._txt.textWidth / 2 - 5;
} // end of for
_loc3._mask_red._txt.text = arrayNameGall[_loc4 - 1];
_loc3._x = Math.floor(_loc6._x + _loc6._mc._txt.textWidth + intervalCat);
if (_loc4 < lenCat)
{
_category._breakers.attachMovie("breaker", "breaker" + _loc4, _loc4);
var _loc7 = _category._breakers["breaker" + _loc4];
_loc7._x = _loc3._x + _loc3._mc._txt.textWidth + intervalBr;
} // end if
_category._x = 881 - _category._width;
_loc3.onRollOver = function ()
{
if (this.index != _root.gallerySel)
{
btnCatOver(this._red, this._arr1);
} // end if
};
_loc3.onRollOut = _loc3.onReleaseOutside = function ()
{
if (this.index != _root.gallerySel)
{
btnCatOut(this._red, this._arr1);
} // end if
};
_loc3.onRelease = function ()
{
if (this.index != _root.gallerySel)
{
btnCatOut(_category["btnCat" + _root.gallerySel]._red, _category["btnCat" + _root.gallerySel]._arr1);
clearThumbs();
caurina.transitions.Tweener.addTween(_thumbs._thumbs, {_y: 0, time: 1, transition: "easeOutCubic"});
yPos = 0;
_root.gallerySel = this.index;
parsXML();
arrayThumbs();
getDes();
mcLoader.loadClip(arrayImage[0], _mc1._mc);
} // end if
};
} // end of for
btnCatOver(_category.btnCat1._red, _category.btnCat1._arr1);
} // End of the function
function btnCatOver(clip1, clip2)
{
caurina.transitions.Tweener.addTween(clip1, {_y: 17, time: 3, transition: "easeOutCubic"});
caurina.transitions.Tweener.addTween(clip2, {_y: -6, time: 5.000000E-001, transition: "easeOutCubic"});
var _loc1 = new Sound();
_loc1.attachSound("bt_snd");
_loc1.start();
} // End of the function
function btnCatOut(clip1, clip2)
{
caurina.transitions.Tweener.addTween(clip1, {_y: -27, time: 3, transition: "easeOutCubic"});
caurina.transitions.Tweener.addTween(clip2, {_y: -24, time: 5.000000E-001, transition: "easeOutCubic"});
} // End of the function
function clearThumbs()
{
for (var _loc1 = 1; _loc1 <= lenGall; ++_loc1)
{
_thumbs._thumbs["thumb" + _loc1].removeMovieClip();
} // end of for
} // End of the function
function getDes()
{
var _loc2 = new Object();
_loc2.onMouseMove = function ()
{
if (_mask_des.hitTest(_root._xmouse, _root._ymouse))
{
caurina.transitions.Tweener.addTween(_descr, {_y: 407, time: 5.000000E-001, transition: "easeOutCubic"});
}
else
{
caurina.transitions.Tweener.addTween(_descr, {_y: 467, time: 5.000000E-001, transition: "easeOutCubic"});
} // end else if
};
Mouse.addListener(_loc2);
_descr._txt.text = arrayTitle[currentIndex];
} // End of the function
_thumbs._thumbs.setMask(_thumbs._mask);
_root.gallerySel = 1;
var lenGall;
var lenCat;
var mainGalleryNode;
var path;
var arrayImage = new Array();
var arrayThumb = new Array();
var arrayTitle = new Array();
var arrayDescription = new Array();
var arrayNameGall = new Array();
var currentIndex = 0;
var descStr;
var titleStr;
var sel = false;
var counter;
var intervalCat = 54;
var intervalBr = intervalCat / 2;
var yPos = 0;
var gallery_xml = new XML();
gallery_xml.ignoreWhite = true;
gallery_xml.onLoad = function (ok)
{
if (ok)
{
parsXML();
arrayThumbs();
menuCat();
getDes(); //Shows the Colour view bar
_mc2._mc.unloadMovie();
mcLoader.loadClip(arrayImage[0], _mc1._mc);
} // end if
};
gallery_xml.load("cgal.xml");
btnTop.onRollOver = btnBottom.onRollOver = function ()
{
this.gotoAndPlay("over");
};
btnTop.onRollOut = btnBottom.onRollOut = function ()
{
this.gotoAndPlay("out");
};
btnBottom.onRelease = function ()
{
if (_thumbs._thumbs._height > _thumbs._mask._height)
{
if (Math.abs(_thumbs._thumbs._y) < _thumbs._thumbs._height - _thumbs._mask._height && caurina.transitions.Tweener.isTweening(_thumbs._thumbs) != true)
{
yPos = yPos - (_thumbs._thumbs.thumb1._height + 1);
caurina.transitions.Tweener.addTween(_thumbs._thumbs, {_y: yPos, time: 5.000000E-001, transition: "easeOutCubic"});
} // end if
} // end if
};
btnTop.onRelease = function ()
{
if (_thumbs._thumbs._height > _thumbs._mask._height)
{
if (Math.abs(_thumbs._thumbs._y) > 0 && caurina.transitions.Tweener.isTweening(_thumbs._thumbs) != true)
{
yPos = yPos + (_thumbs._thumbs.thumb1._height + 1);
caurina.transitions.Tweener.addTween(_thumbs._thumbs, {_y: yPos, time: 5.000000E-001, transition: "easeOutCubic"});
} // end if
} // end if
};
caurina.transitions.properties.ColorShortcuts.init();
_descr._btn_color.onRollOver = function ()
{
caurina.transitions.Tweener.addTween(_mc2._mc, {_saturation: 1, time: 2});
};
_descr._btn_color.onRollOut = function ()
{
caurina.transitions.Tweener.addTween(_mc2._mc, {_saturation: 0, time: 2});
};
var mcLoader = new MovieClipLoader();
var loadListener = new Object();
loadListener.onLoadStart = function (mcTarget)
{
_root.loadImBig = true;
_root._content.pages.page1.page1.attachMovie("mcPercents", "mcPercents", this.getNextHighestDepth());
_root._content.pages.page1.page1.mcPercents._x = _mask_des._width / 2 - 10;
_root._content.pages.page1.page1.mcPercents._y = _mask_des._height / 2 - 25;
};
loadListener.onLoadProgress = function (mcTarget, bytesLoaded, bytesTotal)
{
var _loc2 = Math.ceil(bytesLoaded / bytesTotal * 100);
_root._content.pages.page1.page1.mcPercents.txtPercents.text = _loc2 + "%";
};
loadListener.onLoadComplete = function (mcTarget)
{
_root._content.pages.page1.page1.mcPercents.mcLoading.removeMovieClip();
_root._content.pages.page1.page1.mcPercents.removeMovieClip();
};
loadListener.onLoadInit = function (mcTarget) //Controls the different tabs at the bottom
{
caurina.transitions.Tweener.addTween(_mc2._mc, {_saturation: 0, time: 5.000000E-001});
mask_mc.gotoAndPlay(2);
_white.gotoAndPlay(2);
};
mcLoader.addListener(loadListener);
Edit:
After taking a look at snapplex's project files, it appears the issue may be a difference in behaviour between Flash versions when a mask is completely empty.
The grey saturation has a mask which animates and finishes on a blank frame. This hides the masked object in the test environment (targeting Flash Player 8), but shows the whole object in browser (with the latest player version).
A quick workaround is to add a shape to the mask which is off stage, which leaves the masked object invisible in both player versions.
(My original answer suggested Flash didn't receive rollover events without focus, but this was incorrect.)
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();