easeljs domelement issue with devicePixelRatio - easeljs

Issue already posted here. http://community.createjs.com/discussions/easeljs/22315-domelement-remove-transformsscale
Having problems using DOMElement after I adjust the canvas for devicePixelRatio.
Code looks something like:
stage.canvas.width = width * scalingFactor
stage.canvas.height = height * scalingFactor
stage.canvas.style.width = width
stage.canvas.style.height = height
This gives me nice crisp text on retina screens.
However, positions of DOMElements are now off.
Any ideas? Is this a known error?
Cheers,
Matt.

I ended up with extending the default DOMElement with something like that:
var DOMElement = function(htmlElement) {
this.DOMElement_constructor(htmlElement);
this.globalScale = CanvasUtils.getScale();
this.acceleratedCompositing = Modernizr.csstransforms3d;
};
var p = createjs.extend(DOMElement, createjs.DOMElement);
/**
* #override
*
* Overrides default createjs DOMElement.
*
* overrides _handleDrawEnd
* Sets 3d transform (translateZ)
*/
p._handleDrawEnd = function(evt) {
var o = this.htmlElement;
if (!o) { return; }
var style = o.style;
var props = this.getConcatenatedDisplayProps(this._props), mtx = props.matrix;
// use display instead of visibility
var display = props.visible ? '' : 'none';
if (display != style.display) { style.display = display; }
if (!props.visible) { return; }
var oldProps = this._oldProps, oldMtx = oldProps&&oldProps.matrix;
var n = 10000; // precision
if (!oldMtx || !oldMtx.equals(mtx)) {
var str = '';
if(this.acceleratedCompositing) {
str += 'translateZ(0)';
}
str += "matrix(" + (mtx.a*n|0)/n / this.globalScale +","+ (mtx.b*n|0)/n +","+ (mtx.c*n|0)/n +","+ (mtx.d * n|0)/n / this.globalScale+","+ (mtx.tx + 0.5|0) / this.globalScale;
style.transform = style.WebkitTransform = style.OTransform = style.msTransform = str +","+ (mtx.ty+0.5|0) / this.globalScale +")";
style.MozTransform = str +"px,"+ (mtx.ty+0.5|0) / this.globalScale +"px)";
if (!oldProps) { oldProps = this._oldProps = new createjs.DisplayProps(true, NaN); }
oldProps.matrix.copy(mtx);
}
if (oldProps.alpha != props.alpha) {
style.opacity = ""+(props.alpha*n|0)/n;
oldProps.alpha = props.alpha;
}
};
createjs.DOMElement = createjs.promote(DOMElement, "DOMElement");

Related

Get two offset points between two points

Hi I need help finding coordinate or points offset from two endpoints of a line. In my program, I would like to specify the two points and the offset. Then I need to calculate the two offset coordinates.
I worked something out using trigonometry but it only works in some cases and when the line is in the positive quadrant.
Here is an image describing what I need to find:
Points on line
Ok so I need to find X3,Y3 and X4,Y4 coordinates.
My method I followed:
Calculate angle:
Ang = atan((Y2 - Y1)/(X2 - X1))
To find X3:
X3 = X1 + Offset * Cos(Ang)
The same concept for Y3
The issue is that if the line is in a different quadrant the point info is not correct... Any help, please.
This question is a clear case for using 2d vector math. The idea is that we subtract p1 from p2 to give us a vector that describes the length and direction of the line. We then normalize this vector, such that it has a length of 1. If you then multiply this normalized vector with the number of units you'd like to move away from the end and add the result to the end-point, you'll have a new point.
Consider an example walking along the x axis:
p1 = 0,0
p2 = 10,0
dif = p2 - p1 = (10,0)
length is 10, so it's 10 times too long - we divide it by 10 to get a vector 1 unit long.
If we then move 5 times (1,0), we end up at 5,0 - 5 units away, bewdy!
Here's a function that achieves the same thing:
function calcOffsetPoint(x1,y1, x2,y2, distTowardsP2fromP1)
{
var p1 = new vec2d(x1,y1);
var p2 = new vec2d(x2,y2);
var delta = p2.sub(p1);
var dirVec = delta.clone();
dirVec.normalize();
dirVec.timesEquals(distTowardsP2fromP1);
var resultPoint = p1.add(dirVec);
return resultPoint;
}
As you can see, this makes use of something I've called vec2d. There's a copy of it in the following snippet:
"use strict";
function byId(id){return document.getElemetById(id)}
function newEl(tag){return document.createElement(tag)}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
var end1 = new vec2d(0,0);
var end2 = new vec2d(10,0);
var midPoint = calcOffsetPoint(end1.x,end1.y, end2.x,end2.y, 5);
console.log( midPoint.toStringN(2) );
}
class vec2d
{
constructor(x=0, y=0)
{
this.mX = x;
this.mY = y;
}
get x(){return this.mX;}
set x(newX){this.mX = newX;}
get y(){return this.mY;}
set y(newY){this.mY = newY;}
add(other)
{
return new vec2d(this.x+other.x, this.y+other.y);
}
sub(other)
{
return new vec2d(this.x-other.x, this.y-other.y);
}
timesEquals(scalar)
{
this.x *= scalar;
this.y *= scalar;
return this;
}
divByEquals(scalar)
{
this.x /= scalar;
this.y /= scalar;
return this;
}
dotProd(other)
{
return this.x*other.x + this.y*other.y;
}
length()
{
return Math.hypot(this.x, this.y);
}
normalize()
{
this.divByEquals( this.length() );
return this;
}
perpendicular()
{
var tmp = this.x;
this.x = -this.y;
this.y = tmp;
return this;
}
clone()
{
return vec2d.clone(this);
}
static clone(other)
{
return new vec2d(other.x, other.y);
}
toString(){return `vec2d {x: ${this.x}, y: ${this.y}}`}
toStringN(n){return `vec2d {x: ${this.x.toFixed(n)}, y: ${this.y.toFixed(n)}}`}
}
function calcOffsetPoint(x1,y1, x2,y2, distTowardsP2fromP1)
{
var p1 = new vec2d(x1,y1);
var p2 = new vec2d(x2,y2);
var delta = p2.sub(p1);
var dirVec = delta.clone();
dirVec.normalize();
dirVec.timesEquals(distTowardsP2fromP1);
var resultPoint = p1.add(dirVec);
return resultPoint;
}
I had some spare time over the weekend, so put together a working demo of the image you posted. Have a play around. Make sure you run it in full-screen, so you can see the sliders that set the offsets for p3 and p4. Disregard the coordinate-system transformation stuff, that's just there to allow me to make an image the same dimensions as your image yet conveniently display it in a window with about 5% the area. The questions come from the exercise section of some old text-book I was reading over the weekend.
"use strict";
class vec2d
{
constructor(x=0,y=0)
{
this.x = x;
this.y = y;
}
abs()
{
this.x = Math.abs(this.x);
this.y = Math.abs(this.y);
return this;
}
add(vec1)
{
return new vec2d(this.x+vec1.x, this.y+vec1.y);
}
sub(vec1)
{
return new vec2d(this.x-vec1.x, this.y-vec1.y);
}
mul(scalar)
{
return new vec2d(this.x*scalar, this.y*scalar);
}
plusEquals(vec1)
{
this.x += vec1.x;
this.y += vec1.y;
return this;
}
minusEquals(vec1)
{
this.x -= vec1.x;
this.y -= vec1.y;
return this;
}
timesEquals(scalar)
{
this.x *= scalar;
this.y *= scalar;
return this;
}
divByEquals(scalar)
{
this.x /= scalar;
this.y /= scalar;
return this;
}
normalize()
{
var len = this.length;
this.x /= len;
this.y /= len;
return this;
}
get length()
{
//return Math.sqrt( (this.x*this.x)+(this.y*this.y) );
return Math.hypot( this.x, this.y );
}
set length(newLen)
{
var invLen = newLen / this.length;
this.timesEquals(invLen);
}
dotProd(vec1)
{
return this.x*vec1.x + this.y*vec1.y;
}
perp()
{
var tmp = this.x;
this.x = -this.y;
this.y = tmp;
return this;
}
wedge(other)
{ // computes an area for parallelograms
return this.x*other.y - this.y*other.x;
}
static clone(other)
{
var result = new vec2d(other.x, other.y);
return result;
}
clone() // clone self
{
return vec2d.clone(this);
}
setTo(other)
{
this.x = other.x;
this.y = other.y;
}
get(){ return {x:this.x, y:this.y}; }
toString(){ return `vec2d {x: ${this.x}, y: ${this.y}}` }
toStringN(n){ return `vec2d {x: ${this.x.toFixed(n)}, y: ${this.y.toFixed(n)}}` }
print(){console.log(this.toString())}
};
class mat3
{
static clone(other)
{
var result = new mat3();
other.elems.forEach(
function(el, index, collection)
{
result.elems[index] = el;
}
);
return result;
}
clone()
{
return mat3.clone(this);
}
constructor(a,b,c,d,e,f)
{
if (arguments.length < 6)
this.setIdentity();
else
this.elems = [a,b,0,c,d,0,e,f,1];
}
setIdentity()
{
this.elems = [1,0,0, 0,1,0, 0,0,1];
}
multiply(other, shouldPrepend)
{
var a, b, c = new mat3();
if (shouldPrepend === true)
{
a = other;
b = this;
}
else
{
a = this;
b = other;
}
c.elems[0] = a.elems[0]*b.elems[0] + a.elems[1]*b.elems[3] + a.elems[2]*b.elems[6];
c.elems[1] = a.elems[0]*b.elems[1] + a.elems[1]*b.elems[4] + a.elems[2]*b.elems[7];
c.elems[2] = a.elems[0]*b.elems[2] + a.elems[1]*b.elems[5] + a.elems[2]*b.elems[8];
// row 1
c.elems[3] = a.elems[3]*b.elems[0] + a.elems[4]*b.elems[3] + a.elems[5]*b.elems[6];
c.elems[4] = a.elems[3]*b.elems[1] + a.elems[4]*b.elems[4] + a.elems[5]*b.elems[7];
c.elems[5] = a.elems[3]*b.elems[2] + a.elems[4]*b.elems[5] + a.elems[5]*b.elems[8];
// row 2
c.elems[6] = a.elems[6]*b.elems[0] + a.elems[7]*b.elems[3] + a.elems[8]*b.elems[6];
c.elems[7] = a.elems[6]*b.elems[1] + a.elems[7]*b.elems[4] + a.elems[8]*b.elems[7];
c.elems[8] = a.elems[6]*b.elems[2] + a.elems[7]*b.elems[5] + a.elems[8]*b.elems[8];
for (var i=0; i<9; i++)
this.elems[i] = c.elems[i];
}
transformVec2s(pointList)
{
var i, n = pointList.length;
for (i=0; i<n; i++)
{
var x = pointList[i].x*this.elems[0] + pointList[i].y*this.elems[3] + this.elems[6];
var y = pointList[i].x*this.elems[1] + pointList[i].y*this.elems[4] + this.elems[7];
pointList[i].x = x;
pointList[i].y = y;
}
}
makeTransformedPoints(pointList)
{
var result = [];
for (var i=0,n=pointList.length;i<n;i++)
{
var x = pointList[i].x*this.elems[0] + pointList[i].y*this.elems[3] + this.elems[6];
var y = pointList[i].x*this.elems[1] + pointList[i].y*this.elems[4] + this.elems[7];
result.push( new vec2d(x,y) );
}
return result;
}
rotate(degrees, shouldPrepend)
{
var tmp = new mat3();
tmp.elems[0] = Math.cos( degrees/180.0 * Math.PI );
tmp.elems[1] = -Math.sin( degrees/180.0 * Math.PI );
tmp.elems[3] = -tmp.elems[1];
tmp.elems[4] = tmp.elems[0];
this.multiply(tmp, shouldPrepend);
}
scaleEach(scaleX, scaleY, shouldPrepend)
{
var tmp = new mat3();
tmp.elems[0] = scaleX;
tmp.elems[4] = scaleY;
this.multiply(tmp, shouldPrepend);
}
scaleBoth(scaleAmount, shouldPrepend)
{
var tmp = new mat3();
tmp.elems[0] = scaleAmount;
tmp.elems[4] = scaleAmount;
this.multiply(tmp, shouldPrepend);
}
translate(transX, transY, shouldPrepend)
{
var tmp = new mat3();
tmp.elems[6] = transX;
tmp.elems[7] = transY;
this.multiply(tmp, shouldPrepend);
}
determinant()
{
var result, a, b;
a = ( (this.elems[0]*this.elems[4]*this.elems[8])
+ (this.elems[1]*this.elems[5]*this.elems[6])
+ (this.elems[2]*this.elems[3]*this.elems[7]) );
b = ( (this.elems[2]*this.elems[4]+this.elems[6])
+ (this.elems[1]*this.elems[3]+this.elems[8])
+ (this.elems[0]*this.elems[5]+this.elems[7]) );
result = a - b;
return result;
}
isInvertible()
{
return (this.determinant() != 0);
}
invert()
{
var det = this.determinant();
if (det == 0)
return;
var a,b,c,d,e,f,g,h,i;
a = this.elems[0]; b = this.elems[1]; c = this.elems[2];
d = this.elems[3]; e = this.elems[4]; f = this.elems[5];
g = this.elems[6]; h = this.elems[7]; i = this.elems[8];
this.elems[0] = (e*i - f*h); this.elems[1] = -((b*i) - (c*h)); this.elems[2] = (b*f)-(c*e);
this.elems[3] = -(d*i - f*g); this.elems[4] = (a*i) - (c*g); this.elems[5] = -( (a*f) - (c*d) );
this.elems[6] = (d*h - e*g); this.elems[7] = -((a*h) - (b*g)); this.elems[8] = (a*e)-(b*d);
var detInv = 1.0 / det;
for (var i=0; i<9; i++)
this.elems[i] *= detInv;
return this;
}
reset()
{
this.setIdentity();
}
print()
{
var str = '';
for (var i=0; i<9; i++)
{
if (i && i%3==0)
str += "\n";
str += " " + this.elems[i].toFixed(5);
}
console.log(str);
}
}
function byId(id){return document.getElementById(id)}
function newEl(tag){return document.createElement(tag)}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('output').addEventListener('mousemove', onMouseMove, false);
byId('slider1').addEventListener('input', onSliderInput, false);
byId('slider2').addEventListener('input', onSliderInput, false);
draw();
}
//(400-48)/400 = 0.88
var invMat, svgInvMat;
function onMouseMove(evt)
{
var mousePos = new vec2d(evt.offsetX,evt.offsetY);
var worldPos = mousePos.clone();
invMat.transformVec2s( [worldPos] );
byId('screenMouse').textContent = `screen: ${mousePos.x},${mousePos.y}`;
byId('worldMouse').textContent = `world: ${worldPos.x.toFixed(1)}, ${worldPos.y.toFixed(1)}`;
}
function onSliderInput(evt)
{
draw();
}
function updateSliderLabels()
{
byId('ofset1Output').textContent = byId('slider1').value;
byId('ofset2Output').textContent = byId('slider2').value;
}
function draw()
{
var can = byId('output');
var ctx = can.getContext('2d');
ctx.clearRect(0,0,can.width,can.height);
var orientMat = evaluateViewOrientationMatrix(0.06*can.width,can.height-24, 0,-1);
var scaleMat = computeWindowToViewPortMatrix(2052,1317, can.width,can.height);
var viewMat = scaleMat.clone();
viewMat.multiply(orientMat);
console.log('viewMat');
viewMat.print();
invMat = viewMat.clone().invert();
for (var i=0; i<9; i++)
invMat.elems[i] /= invMat.elems[8];
ctx.strokeStyle = '#fff';
var axisPts = [ new vec2d(0,1070), new vec2d(0,0), new vec2d(0.88*2052,0) ]; // xAxis line 88% of image width
var axis = viewMat.makeTransformedPoints(axisPts);
drawLine(axis[0].x,axis[0].y, axis[1].x,axis[1].y, ctx);
drawLine(axis[1].x,axis[1].y, axis[2].x,axis[2].y, ctx);
var lineEnds = [new vec2d(330,263), new vec2d(1455,809)];
var pts2 = viewMat.makeTransformedPoints(lineEnds);
drawCircle(pts2[0].x,pts2[0].y, 4, ctx);
drawCircle(pts2[1].x,pts2[1].y, 4, ctx);
drawLine(pts2[0].x,pts2[0].y, pts2[1].x,pts2[1].y, ctx);
var rawP3 = calcOffsetCoords(lineEnds[0].x,lineEnds[0].y, lineEnds[1].x,lineEnds[1].y, byId('slider1').value);
var rawP4 = calcOffsetCoords(lineEnds[1].x,lineEnds[1].y, lineEnds[0].x,lineEnds[0].y, byId('slider2').value);
var ofsPts = viewMat.makeTransformedPoints( [rawP3, rawP4] );
drawCircle(ofsPts[0].x,ofsPts[0].y, 4, ctx);
drawCircle(ofsPts[1].x,ofsPts[1].y, 4, ctx);
updateSliderLabels();
}
function calcOffsetCoords(x1,y1, x2,y2, offset)
{
var dx = x2 - x1;
var dy = y2 - y1;
var lineLen = Math.hypot(dx, dy);
var normDx=0, normDy=0;
if (lineLen != 0)
{
normDx = dx / lineLen;
normDy = dy / lineLen;
}
var resultX = x1 + (offset * normDx);
var resultY = y1 + (offset * normDy);
return {x:resultX,y:resultY};//new vec2d(resultX,resultY); //{x:resultX,y:resultY};
}
// Exercise 6-1:
// Write a procedure to implement the evaluateViewOrientationMatrix function that calculates the elements of the
// matrix for transforming world coordinates to viewing coordinates, given the viewing coordinate origin Porigin and
// the viewUp vector
function evalViewOrientMatrix(screenOriginX,screenOriginY, worldUpVectorX,worldUpVectorY)
{
var worldUp = {x: worldUpVectorX, y: worldUpVectorY};
var len = Math.hypot(worldUp.x, worldUp.y);
if (len != 0)
len = 1.0 / len;
worldUp.x *= len;
worldUp.y *= len;
var worldRight = {x: worldUp.y, y: -worldUp.x};
var rotMat = svg.createSVGMatrix();
rotMat.a = worldRight.x;
rotMat.b = worldRight.y;
rotMat.c = worldUp.x;
rotMat.d = worldUp.y;
var transMat = svg.createSVGMatrix();
transMat = transMat.translate(screenOriginX, screenOriginY);
var result = rotMat.multiply(transMat);
return result;
}
function evaluateViewOrientationMatrix(screenOriginX,screenOriginY, worldUpVectorX,worldUpVectorY)
{
var worldUp = new vec2d(worldUpVectorX, worldUpVectorY);
worldUp.normalize();
var worldRight = worldUp.clone().perp();
var rotMat = new mat3();
rotMat.elems[0] = worldRight.x; rotMat.elems[1] = worldRight.y;
rotMat.elems[3] = worldUp.x; rotMat.elems[4] = worldUp.y;
var transMat = new mat3();
transMat.translate(screenOriginX,screenOriginY);
var result = rotMat.clone();
result.multiply(transMat);
return result;
}
/*
0 1 2
3 4 5
6 7 8
translation
-----------
1 0 0
0 1 0
tX tY 1
scaling
---------
sX 0 0
0 sY 0
0 0 1
rotation
--------
cosX -sinX 0
sinX cosX 0
0 0 1
*/
// Exercise 6-2:
// Derive the window to viewport transformation equations 6-3 by first scaling the window to
// the size of the viewport and then translating the scaled window to the viewport position
function computeWindowToViewPortMatrix(windowWidth,windowHeight,viewPortWidth,viewPortHeight)
{
var result = new mat3();
result.scaleEach(viewPortWidth/windowWidth,viewPortHeight/windowHeight);
return result;
}
// returns an SVGMatrix
function compWnd2ViewMat(windowWidth,windowHeight,viewPortWidth,viewPortHeight)
{
var result = svg.createSVGMatrix();
return result.scaleNonUniform(viewPortWidth/windowWidth,viewPortHeight/windowHeight);
}
function drawLine(x1,y1,x2,y2,ctx)
{
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
function drawCircle(x,y,radius,ctx)
{
ctx.beginPath();
ctx.arc(x, y, radius, 0, (Math.PI/180)*360, false);
ctx.stroke();
ctx.closePath();
}
canvas
{
background-color: black;
}
.container
{
display: inline-block;
background-color: #888;
border: solid 4px #555;
}
#screenMouse, #worldMouse, .control
{
display: inline-block;
width: calc(513px/2 - 2*8px);
margin-left: 8px;
}
<body>
<div class='container'>
<canvas id='output' width='513' height='329'></canvas><br>
<div id='screenMouse'></div><div id='worldMouse'></div>
<div>
<div class='control'>P2 ofs: <input id='slider1' type='range' min='0' max='500' value='301'><span id='ofset1Output'></span></div>
<div class='control'>P3 ofs: <input id='slider2' type='range' min='0' max='500' value='285'><span id='ofset2Output'></span></div>
</div>
</div>
</body>

Chart.js click on labels, using bar chart

i need help with my Chart.js interactivity. When I click on the label, I need to return the column(index) number at which I clicked.
I tried to use getElementsAtEvent but it only work if I click directly at chart.
This http://jsfiddle.net/yxz2sjam/ is pretty much what I am looking for but getPointsAtEvent is no longer available in the new versions.
canvas.onclick = function (evt) {
var points = chart.getPointsAtEvent(evt);
alert(chart.datasets[0].points.indexOf(points[0]));
};
I also found this http://jsfiddle.net/1Lngmtz7/ but it isn't working with bar chart.
var ctx = document.getElementById("myChart").getContext("2d");
var myRadarChart = new Chart(ctx, {
type: 'radar',
data: data
})
$('#myChart').click(function (e) {
var helpers = Chart.helpers;
var eventPosition = helpers.getRelativePosition(e, myRadarChart.chart);
var mouseX = eventPosition.x;
var mouseY = eventPosition.y;
var activePoints = [];
helpers.each(myRadarChart.scale.ticks, function (label, index) {
for (var i = this.getValueCount() - 1; i >= 0; i--) {
var pointLabelPosition = this.getPointPosition(i, this.getDistanceFromCenterForValue(this.options.reverse ? this.min : this.max) + 5);
var pointLabelFontSize = helpers.getValueOrDefault(this.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize);
var pointLabeFontStyle = helpers.getValueOrDefault(this.options.pointLabels.fontStyle, Chart.defaults.global.defaultFontStyle);
var pointLabeFontFamily = helpers.getValueOrDefault(this.options.pointLabels.fontFamily, Chart.defaults.global.defaultFontFamily);
var pointLabeFont = helpers.fontString(pointLabelFontSize, pointLabeFontStyle, pointLabeFontFamily);
ctx.font = pointLabeFont;
var labelsCount = this.pointLabels.length,
halfLabelsCount = this.pointLabels.length / 2,
quarterLabelsCount = halfLabelsCount / 2,
upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
var width = ctx.measureText(this.pointLabels[i]).width;
var height = pointLabelFontSize;
var x, y;
if (i === 0 || i === halfLabelsCount)
x = pointLabelPosition.x - width / 2;
else if (i < halfLabelsCount)
x = pointLabelPosition.x;
else
x = pointLabelPosition.x - width;
if (exactQuarter)
y = pointLabelPosition.y - height / 2;
else if (upperHalf)
y = pointLabelPosition.y - height;
else
y = pointLabelPosition.y
if ((mouseY >= y && mouseY <= y + height) && (mouseX >= x && mouseX <= x + width))
activePoints.push({ index: i, label: this.pointLabels[i] });
}
}, myRadarChart.scale);
var firstPoint = activePoints[0];
if (firstPoint !== undefined) {
alert(firstPoint.index + ': ' + firstPoint.label);
}
});
Thank for response.
I solve the problem with
document.getElementById("chart").onclick = function(e)
{
var activeElement = weatherMainChart.lastTooltipActive;
console.log(activeElement[0]._index);
};
this solution register clicks on chart and label, then I restricted it with e.layerY to register only clicks on label section.
document.getElementById("chart").onclick = function(e)
{
var activeElement = weatherMainChart.lastTooltipActive;
if(e.layerY > 843 && e.layerY < 866 && activeElement[0] !== undefined)
console.log(activeElement[0]._index);
};
If you add a click handler through the onClick option you can use the following code using the getElementsAtEventForMode() call:
function handleClick(evt) {
var col;
switch(chartType) {
case "horizontalBar":
this.getElementsAtEventForMode(evt, "y", 1).forEach(function(item) { col = item._index });
break;
case "bar":
this.getElementsAtEventForMode(evt, "x", 1).forEach(function(item) { col = item._index });
break;
}
if (!col) {
return;
}
alert("Column " + col + " was selected");
};
You'll probably need to add extra switch checks for other chart types but I'm sure you get the idea.
Using version 2.4.0, i created an onClick Event, and inside it
var activeIndex = localChart.tooltip._lastActive[0]._index;
var clickCoordinates = Chart.helpers.getRelativePosition(e, localChart.chart);
if (clickCoordinates.y >= 530) { //custom value, depends on chart style,size, etc
alert("clicked on " + localChart.data.labels[activeIndex]);
}
I Solved this problem with single or multiple label click you will be find using true/false
First you need to set your chartJs Id click
below code SessionChart = Your ChartJs ID e.g. ("myChart") I was replace it for my Id
document.getElementById("SessionChart").onclick = function (evt) {
var meta = SubscriberSessionChart.getDatasetMeta(0);
if (meta.$filler.chart.legend.legendItems[0].text.toLowerCase() "sessions")
{
if (meta.$filler.chart.legend.legendItems[0].hidden) {
sessionHidden = true;
}
}
}
here "sessions" = first label text
meta.$filler.chart.legend.legendItems[0].text.toLowerCase() = is your first label
from Array so you can get multiple label's click here true / false
if (meta.$filler.chart.legend.legendItems[0].hidden) = your label is not active then
you will get hidden true otherwise you will get false if not tick on label
by default label tick hidden is false in chart js

Trouble looping and remove createjs "on" eventListener with "off"

Im trying to loop and remove eventlistener in createjs:
Actor = function() {
this.update = true;
this.offset;
this.instance;
this.member = function(a_obj) {
count++;
this._container = a_obj.container;
this._images = a_obj.images;
this._name = a_obj.name;
this._top = a_obj.top;
this._left = a_obj.left;
getCirTest = new createjs.Bitmap(loader.getResult(this._images));
getCirTest.name = this._name;
getCirTest.y = this._top + 10;
getCirTest.x = this._left + 10;
getCirTest.scaleX = 0.8;
getCirTest.scaleY = 0.8;
getCirTest.cursor = "pointer";
this._container.addChild(getCirTest);
holdsAllObj[count]=getCirTest;
console.log(holdsAllObj);
md = getCirTest.on("mousedown", activate);
function activate(evt) {
myCurrentTarget = evt.currentTarget;
xyCor.push(evt.currentTarget.x, evt.currentTarget.y);
this.parent.addChild(this);
this.offset = {
x: this.x - evt.stageX,
y: this.y - evt.stageY
};
}
pm = getCirTest.on("pressmove", move);
function move(evt) {
myintersect(evt.currentTarget, getCenterBitmap);
this.x = evt.stageX + this.offset.x;
this.y = evt.stageY + this.offset.y;
update = true;
}
cc = getCirTest.on("click", release);
function release (evt) {
countClicks++;
holdsAllObj[1].off("mousedown",md);
holdsAllObj[1].off("pressmove",pm);
console.log();
if (soundPlay == true && countClicks == 1) {
console.log("im true");
mySoundInstance = createjs.Sound.play(evt.currentTarget.name);
mySoundInstance.addEventListener("complete", createjs.proxy(handleSoundComplete, mySoundInstance));
} else {
createjs.Sound.stop(evt.currentTarget.name);
countClicks = 0;
}
console.log(countClicks);
update = true;
}
} //**** END: members ****
}
Its my getCirTest, whichs have an event:
md = getCirTest.on("mousedown", activate);
It´s create 10 instance of a bitmap object like this:
for (var circles = 0; circles < 10; circles++) {
var x = Math.round(container.width / 2 + radius * Math.cos(angle) - 150 / 2);
var y = Math.round(container.width / 2 + radius * Math.sin(angle) - 150 / 2);
var MP = new Actor();
MP.member({
container: container,
images: myFTMImages[circles],
name: myFTMNames[circles],
top: y,
left: x
});
angle += step;
}
My problem is that i would like to remove the eventListeners in a event:
cc = getCirTest.on("click", release);
function release (evt) {
}
Thats why i have put the bitmaps in a array:
holdsAllObj[count]=getCirTest;
And then tried the following:
cc = getCirTest.on("click", release);
function release (evt) {
for(var ijk=0;ijk<holdsAllObj.length;ijk++){
holdsAllObj[ijk].off("mousedown",md);
holdsAllObj[ijk].off("pressmove",pm);
}
}
unfortunately .. it´does not work for me ...
This looks like an issue with js scope. JS methods are called in the window context rather than the context they are created. You can use the createjs.proxy method to apply a scope to a method call, like this:
cc = getCirTest.on("click", release, this);
Hope that helps.

drag and drop using Starling

I am have difficulty getting drop and drop to work using Starling with feathers ui.
Here is my code:
function begin(){
var quadx = squareSize/4 + squareSize/8;
var quady = 20;
var quadcounter = 0;
for(var f=0;f<totalsquares;f++){
var sprite:Sprite = new Sprite();
var quad:Quad = new Quad(squareSize, squareSize);
sprite.name = "" + f;
spriteunder.name = "" + f * 1000;
quad.setVertexColor(0, 0x3683ed);
quad.setVertexColor(1, 0x3683ed);
quad.setVertexColor(2, 0x3683ed);
quad.setVertexColor(3, 0x3683ed);
sprite.x=quadx;
sprite.y = quady;
var lv3 = new TextField(squareSize, squareSize, f,"Corpid", 14,0xf1f1f1);
sprite.touchable = true;
quad.touchable = true;
lv3.touchable = false;
sprite.addChild(quad);
sprite.addChild(lv3);
addChild(sprite);
sprite.addEventListener(TouchEvent.TOUCH, touchHandler);
quadx = quadx + squareSize + 1;
quadcounter++;
if(quadcounter == boardWidth){
quadx = squareSize/4 + squareSize/8;
quady = quady + squareSize + 1;
quadcounter = 0;
}
}
}
function touchHandler(e : TouchEvent) : void
{
var touch:Touch = e.getTouch(stage);
var position:Point = touch.getLocation(stage);
var target:Quad = e.target as Quad;
if(touch.phase == TouchPhase.MOVED ){
target.x = position.x - target.width/2;
target.y = position.y - target.height/2;
}
}
The problem is that whenever i run this , its the QUAD child that gets dragged around, not the parent sprite.
What do i change in order to get this to drag correctly.
Perhaps you must start with
var touch:Touch = event.getTouch(this, TouchPhase.BEGAN);
if (touch)
{
//get and lock your target, maybe a trace of your actual target, just to be sure!
}
And then in the MOVED phase, actually drag it.

flickr photobar - get description

I implemented this jquery http://tympanus.net/Tutorials/FlickrPhotobarGallery/ and I can capture setname and title but I need to get description too, so I would like to know if this is possible.
Hope someone can help me, thanks in advance!
$(function() {
var api_key = '######';
var user_id = '####';
/*
use:
Square,Thumbnail,Small,Medium or Original for the large image size you want to load!
*/
var large_image_size = 'Medium';
/*
the current Set id / the current Photo id
*/
var photo_set_id,photo_id;
var current = -1;
var continueNavigation = false;
/*
flickr API Call to get List of Sets
*/
var sets_service = 'http://api.flickr.com/services/rest/?&method=flickr.photosets.getList' + '&api_key=' + api_key;
var sets_url = sets_service + '&user_id=' + user_id + '&format=json&jsoncallback=?';
/*
flickr API Call to get List of Photos from a Set
*/
var photos_service = 'http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos' + '&api_key=' + api_key;
/*
flickr API Call to get List of Sizes of a Photo
*/
var large_photo_service = 'http://api.flickr.com/services/rest/?&method=flickr.photos.getSizes' + '&api_key=' + api_key;
/*
elements caching...
*/
var $setsContainer = $('#sets').find('ul');
var $photosContainer = $('#images').find('ul');
var $photopreview = $('#flickr_photopreview');
var $flickrOverlay = $('#flickr_overlay');
var $loadingStatus = $('#flickr_toggle').find('.loading_small');
var ul_width,spacefit,fit;
add: LoadSets();
/* start: open Flickr Photostream */
$('#flickr_toggle').toggle(function(){
$('#photobar').stop().animate({'bottom':'0px'},200,function(){
if($setsContainer.is(':empty')){
/*
if sets not loaded, load them
*/
LoadSets();
}
});
},function(){
/*
minimize the main bar, and minimize the photos bar.
next time we maximize, the view will be on the sets
*/
$('#photobar').stop().animate({'bottom':'-96px'},200,function(){
$('#images').css('bottom','-125px');
});
});
/*
Loads the User Photo Sets
*/
function LoadSets(){
$loadingStatus.css('visibility','visible');
$.getJSON(sets_url,function(data){
if(data.stat != 'fail') {
var sets_count = data.photosets.photoset.length;
/*
adapt ul width based on number of results
*/
ul_width = sets_count * 105 + 105;
$setsContainer.css('width',ul_width + 'px');
for(var i = 0; i < sets_count; ++i){
var photoset = data.photosets.photoset[i];
var primary = photoset.primary;
var secret = photoset.secret;
var server = photoset.server;
var farm = photoset.farm;
/*
source for the small thumbnail
*/
var photoUrl = 'http://farm'+farm+'.static.flickr.com/'+server+'/'+primary+'_'+secret+'_s.jpg';
var $elem = $('<li />');
var $link = $('<a class="toLoad" href="#" />');
/*
save the info of the set in the li element,
we will use it later
*/
$link.data({
'primary' :primary,
'secret' :secret,
'server' :server,
'farm' :farm,
'photoUrl' :photoUrl,
'setName' :photoset.title._content,
'id' :photoset.id
});
$setsContainer.append($elem.append($link));
$link.bind('click',function(e){
var $this = $(this);
/*
save the current Set id in the photo_set_id variable
and load the photos of that Set
*/
$('#images').stop().animate({'bottom':'0px'},200);
if(photo_set_id!=$this.data('id')){
photo_set_id = $this.data('id');
$('#setName').html($this.data('setName'));
LoadPhotos();
}
e.preventDefault();
});
}
/*
now we load the images
(the ones in the viewport)
*/
LoadSetsImages();
}
});
}
/*
loads the images of the sets that are in the viewport
*/
function LoadSetsImages(){
var toLoad = $('.toLoad:in-viewport').size();
if(toLoad > 0)
$loadingStatus.css('visibility','visible');
var images_loaded = 0;
$('.toLoad:in-viewport').each(function(i){
var $space = $setsContainer.find('.toLoad:first');
var $img = $('<img style="display:none;" />').load(function(){
++images_loaded;
if(images_loaded == toLoad){
$loadingStatus.css('visibility','hidden');
$setsContainer.find('img').fadeIn();
}
}).error(function(){
//TODO
++images_loaded;
if(images_loaded == toLoad){
$loadingStatus.css('visibility','hidden');
$setsContainer.find('img').fadeIn();
}
}).attr('src',$space.data('photoUrl')).attr('alt',$space.data('id'));
var $set_name = $('<span />',{'html':$space.data('setName')});
$space.append($set_name).append($img).removeClass('toLoad');
});
}
/*
Loads the Set's Photos
*/
function LoadPhotos(){
$photosContainer.empty();
$loadingStatus.css('visibility','visible');
var photos_url = photos_service + '&photoset_id=' + photo_set_id + '&media=photos&format=json&jsoncallback=?';
$.getJSON(photos_url,function(data){
if(data.stat != 'fail') {
var photo_count = data.photoset.photo.length;
/*
adapt ul width based on number of results
*/
var photo_count_total = photo_count + $photosContainer.children('li').length;
ul_width = photo_count_total * 105 + 105;
$photosContainer.css('width',ul_width + 'px');
for(var i = 0; i < photo_count; ++i){
var photo = data.photoset.photo[i];
var photoid = photo.id;
var secret = photo.secret;
var server = photo.server;
var farm = photo.farm;
var photoUrl = 'http://farm'+farm+'.static.flickr.com/'+server+'/'+photoid+'_'+secret+'_s.jpg';
var $elem = $('<li />');
var $link = $('<a class="toLoad" href="#" />');
$link.data({
'photoid' :photoid,
'secret' :secret,
'server' :server,
'farm' :farm,
'photoUrl' :photoUrl,
'photo_title' :photo.title
});
$photosContainer.append($elem.append($link));
$link.bind('click',function(e){
var $this = $(this);
current = $this.parent().index();
photo_id = $this.data('photoid');
LoadLargePhoto();
e.preventDefault();
});
}
LoadPhotosImages();
}
});
}
/*
loads the images of the set's
photos that are in the viewport
*/
function LoadPhotosImages(){
var toLoad = $('.toLoad:in-viewport').size();
if(toLoad > 0)
$loadingStatus.css('visibility','visible');
var images_loaded = 0;
$('.toLoad:in-viewport').each(function(i){
var $space = $photosContainer.find('.toLoad:first');
var $img = $('<img style="display:none;" />').load(function(){
++images_loaded;
if(images_loaded == toLoad){
$loadingStatus.css('visibility','hidden');
$photosContainer.find('img').fadeIn();
/*
if we were navigating through the large images set:
*/
if(continueNavigation){
continueNavigation = false;
var $thumb = $photosContainer.find('li:nth-child(' + parseInt(current + 1) + ')').find('img');
photo_id = $thumb.attr('alt');
LoadLargePhoto();
}
}
}).error(function(){
//TODO
++images_loaded;
if(images_loaded == toLoad){
$loadingStatus.css('visibility','hidden');
$photosContainer.find('img').fadeIn();
/*
if we were navigating through the large images set:
*/
if(continueNavigation){
continueNavigation = false;
var $thumb = $photosContainer.find('li:nth-child(' + parseInt(current + 1) + ')').find('img');
photo_id = $thumb.attr('alt');
LoadLargePhoto();
}
}
}).attr('src',$space.data('photoUrl'))
.attr('alt',$space.data('photoid'));
var $photo_title = $('<span/>',{'html':$space.data('photo_title')});
$space.append($photo_title).append($img).removeClass('toLoad');
});
}
/*
loads the main image
*/
function LoadLargePhoto(){
removeLargeImage();
var $theThumb = $photosContainer.find('li:nth-child(' + parseInt(current + 1) + ')').find('img');
var photo_title = $theThumb.parent().data('photo_title');
var $loading = $photopreview.find('.loading');
$loading.show();
$photopreview.show();
$flickrOverlay.show();
$('#preview_close').show();
var large_photo_url = large_photo_service + '&photo_id=' + photo_id + '&format=json&jsoncallback=?';
$.getJSON(large_photo_url,function(data){
if(data.stat != 'fail') {
var count_sizes = data.sizes.size.length;
var largest_photo_src;
for(var i = 0; i < count_sizes; ++i){
if(data.sizes.size[i].label == large_image_size)
largest_photo_src = data.sizes.size[i].source;
}
$('<img />').load(function(){
var $this = $(this);
/*
resize the image to fit in the browser's window
*/
resize($this);
$loading.hide();
/*just to make sure theres no image:*/
removeLargeImage();
$photopreview.find('.preview').append($this);
$('#large_phototitle').empty().html(photo_title);
}).attr('src',largest_photo_src);
}
});
}
/*
close the Large Image View
*/
$('#preview_close').bind('click',function(){
$photopreview.hide();
$flickrOverlay.hide();
$('#preview_close').hide();
$('#large_phototitle').empty()
removeLargeImage();
});
/*
removes the large image from the DOM
*/
function removeLargeImage(){
$photopreview.find('img').remove();
}
/*
events to navigate through the Large Images
*/
$('#preview_img_next').bind('click',function(e){
/*
get the next one
*/
++current;
var $link = $photosContainer.find('li:nth-child(' + parseInt(current + 1) + ')');
var $thumb = $link.find('img');
/*
if the next image is not loaded,
we need to scroll the photos container
and just then continue with the navigation
*/
if(!$thumb.length && $link.length){
continueNavigation = true;
removeLargeImage();
$photopreview.find('.loading').show();
$('#images').find('.next').trigger('click');
}
else if(!$thumb.length && !$link.length){
--current;
return;
}
else{
photo_id = $thumb.attr('alt');
LoadLargePhoto();
}
e.preventDefault();
});
$('#preview_img_prev').bind('click',function(e){
/*
get the previous one
*/
var $link = $photosContainer.find('li:nth-child(' + parseInt(current) + ')');
--current;
var $thumb = $link.find('img');
/*
if the previous image is not in the viewport,
we need to scroll the photos container
and just then continue with the navigation
*/
if(!$thumb.length && !$link.length){
++current;
return;
}
if(!$thumb.is(':in-viewport') && $link.length){
$('#images').find('.prev').trigger('click');
}
photo_id = $thumb.attr('alt');
LoadLargePhoto();
e.preventDefault();
});
/*
events to navigate through the sets / photos containers
*/
var scrollAllow = true;
$('#sets,#images').find('.next').bind('click',function(e) {
var target_id = $(e.target).parent().attr('id');
var $theContainer;
if(target_id == 'sets')
$theContainer = $setsContainer;
else if(target_id == 'images')
$theContainer = $photosContainer;
if(scrollAllow){
scrollAllow = false;
spacefit = $(window).width() -44;
fit = Math.floor(spacefit / 105);
var left = parseFloat($theContainer.css('left'),10);
var moveleft = left - (fit*105);
if(ul_width - Math.abs(left) < $(window).width()){
scrollAllow = true;
e.preventDefault();
return;
}
$theContainer.animate({'left':moveleft+'px'},1000,function(){
scrollAllow = true;
if(target_id == 'sets')
LoadSetsImages();
else if(target_id == 'images')
LoadPhotosImages();
});
e.preventDefault();
}
});
$('#sets,#images').find('.prev').bind('click',function(e) {
var target_id = $(e.target).parent().attr('id');
var $theContainer;
if(target_id == 'sets')
$theContainer = $setsContainer;
else if(target_id == 'images')
$theContainer = $photosContainer;
if(scrollAllow){
scrollAllow = false;
spacefit = $(window).width() -44;
fit = Math.floor(spacefit / 105);
var left = parseFloat($theContainer.css('left'),10);
var moveleft = left + (fit*105);
if(left >= 0){
scrollAllow = true;
e.preventDefault();
return;
}
$theContainer.animate({'left':moveleft+'px'},1000,function(){
scrollAllow = true;
});
e.preventDefault();
}
});
/*
when cliking "Back to Sets"
minimize photos bar
*/
$('#images_toggle').bind('click',function(){
$('#images').stop().animate({'bottom':'-125px'},200);
});
/*
when resizing the window, resize the main image
*/
$(window).bind('resize', function() {
var $theLargeImage = $photopreview.find('img');
if($theLargeImage.length)
resize($theLargeImage);
});
/*
resizes the main image based on the windows sizes
*/
function resize($image){
var widthMargin = 10
var heightMargin = 60;
var windowH = $(window).height()-heightMargin;
var windowW = $(window).width()-widthMargin;
$photopreview.find('.preview').css({'width':$(window).width()+'px','height':($(window).height()-25)+'px'});
var theImage = new Image();
theImage.src = $image.attr("src");
var imgwidth = theImage.width;
var imgheight = theImage.height;
if((imgwidth > windowW)||(imgheight > windowH)){
if(imgwidth > imgheight){
var newwidth = windowW;
var ratio = imgwidth / windowW;
var newheight = imgheight / ratio;
theImage.height = newheight;
theImage.width = newwidth;
if(newheight>windowH){
var newnewheight= windowH;
var newratio = newheight/windowH;
var newnewwidth = newwidth/newratio;
theImage.width = newnewwidth;
theImage.height = newnewheight;
}
}
else{
var newheight = windowH;
var ratio = imgheight / windowH;
var newwidth = imgwidth / ratio;
theImage.height = newheight;
theImage.width= newwidth;
if(newwidth>windowW){
var newnewwidth = windowW;
var newratio = newwidth/windowW;
var newnewheight =newheight/newratio;
theImage.height = newnewheight;
theImage.width= newnewwidth;
}
}
}
$image.css({'width':theImage.width+'px','height':theImage.height+'px'});
}
});
If you want the description of a set you can call flickr.photosets.getInfo.
On an unrelated note, you can save an API call to flickr.photos.getSizes for each photo in the set by passing in an extras parameter specifying all of the urls you'd like to get back when calling flickr.photosets.getPhotos. For any size identifier (sq, t, m, l, o, etc.), just pass in an extra of url_(identifier) (so, url_o would have the response contain the original url if it was available). This is documented here: http://www.flickr.com/services/api/flickr.photosets.getPhotos.html