cocos2d-html5 can't make a basic ccmenu work - cocos2d-iphone

Sorry if this is a newbie question but I have just started using cocos2d-html and I am having some issues creating a ccmenu with an image. Here is my code:
var ActionLayer = cc.Layer.extend({
getTexture: function (name) {
return cc.TextureCache.getInstance()
.addImage('./images/' + name + '.png');
},
addObject: function (desc) {
var sprite = cc.Sprite.createWithTexture(this.getTexture(desc.name));
sprite.setAnchorPoint(desc.anchor || cc.p(0.5, 0.5));
sprite.setScaleX(desc.scaleX || desc.scale || 1);
sprite.setScaleY(desc.scaleY || desc.scale || 1);
sprite.setRotation(desc.rotation || 0);
sprite.setPosition(cc.p(desc.x || 0, desc.y || 0));
this.addChild(sprite, desc.z || 0);
return sprite;
},
checkAnswer:function(){
alert('yay');
},
init: function () {
this._super();
this.removeAllChildrenWithCleanup(true);
this.setTouchEnabled(true);
var layer1 = cc.LayerColor.create(
new cc.Color4B(00, 185, 214, 255), 1024, 768);
layer1.setPosition(new cc.Point(0.0,0.0));
this.addChild(layer1,-2);
var director = cc.Director.getInstance(),
self = this,
winSize = director.getWinSize();
var bgSprite = this.addObject({
name: "GenericBG",
scaleY: 1,
anchor: cc.p(0, 0),
z: 0
});
var closeItem = cc.MenuItemImage.create('./images/sign.png','./images/sign.png',this,'checkAnswer');
closeItem.setAnchorPoint(cc.p(0.5, 0.5));
var menu = cc.Menu.create(closeItem);
menu.setPosition(500,300);
this.addChild(menu, 5);
}
}); //end ActionLayer
//--------------------- Scene ---------------------
var ActionLayerScene = cc.Scene.extend({
onEnter: function () {
this._super();
var layer = new ActionLayer();
layer.init();
this.addChild(layer);
}
});
The menu is displayed on the screen but when I click on the menuitem, nothing happens
There is no javascript error on the console so I really don't know how to debug this.
Thanks
Cyril

Your parameter for cc.MenuItemImage.create() is wrong. Instead of:
var closeItem = cc.MenuItemImage.create('./images/sign.png','./images/sign.png',this,'checkAnswer');
it should be:
var closeItem = cc.MenuItemImage.create('./images/sign.png','./images/sign.png','checkAnswer', this);

for(var i=0; i<5; i++){
var colorImg = cc.MenuItemImage.create(color_list[i], color_list[i], "colorAction", this);
colorImg.setPosition(new cc.Point(40+i*70, 38));
colorImg.tag = i+100;
this.colorImageArray.push(colorImg);
colorMenu.addChild(colorImg);
}
colorAction:function(event)
{
var colorTag = event.tag;
switch(colorTag)
{
case 1:
break;
case 2:
break;
case 3:
break;
}
}

Related

create custom IfcPolygonalFaceSet wall using xbim library

I want to create polygonfaceset wall using xbim toolkit library. Please let me know what I am doing wrong. It will be great help to me if anybody can provide sample code or some approach regarding polygonfaceset wall.
Below I provide scrennshot and samplecode.
static private IfcWallStandardCase CreateWall(IfcStore model, double length, double width, double height)
{
//
//begin a transaction
using (var txn = model.BeginTransaction("Create Wall"))
{
var wall = model.Instances.New();
wall.Name = "A Standard rectangular wall";
//represent wall as a rectangular profile
var rectProf = model.Instances.New<IfcRectangleProfileDef>();
rectProf.ProfileType = IfcProfileTypeEnum.AREA;
rectProf.XDim = width;
rectProf.YDim = length;
var insertPoint = model.Instances.New<IfcCartesianPoint>();
insertPoint.SetXY(0, 400); //insert at arbitrary position
rectProf.Position = model.Instances.New<IfcAxis2Placement2D>();
rectProf.Position.Location = insertPoint;
var polyfaceset = model.Instances.New<IfcPolygonalFaceSet>();
var coordinates2 = model.Instances.New<IfcIndexedPolygonalFace>();
//var coordinates = model.Instances.New<IfcCartesianPointList3D>(pl => {
// pl.CoordList.GetAt(0).AddRange(new IfcLengthMeasure[] { 0, 0, 0 });
// pl.CoordList.GetAt(1).AddRange(new IfcLengthMeasure[] { 1, 0, 0 });
// pl.CoordList.GetAt(2).AddRange(new IfcLengthMeasure[] { 0, 1, 0 });
// pl.CoordList.GetAt(3).AddRange(new IfcLengthMeasure[] { 0, 0, 1 });
//});
polyfaceset.Closed = true;
polyfaceset.Coordinates = model.Instances.New<IfcCartesianPointList3D>(pl => {
pl.CoordList.GetAt(0).AddRange(new IfcLengthMeasure[] { 0, 0, 1000 });
pl.CoordList.GetAt(1).AddRange(new IfcLengthMeasure[] { 3000, 0, 1000 });
pl.CoordList.GetAt(2).AddRange(new IfcLengthMeasure[] { 3000, 2000, 10000 });
pl.CoordList.GetAt(3).AddRange(new IfcLengthMeasure[] { 1000, 3000, 1000 });
pl.CoordList.GetAt(4).AddRange(new IfcLengthMeasure[] { 0, 2000, 1000 });
});
//model as a swept area solid
var body = model.Instances.New<IfcExtrudedAreaSolid>();
body.Depth = height;
body.SweptArea = rectProf;
body.ExtrudedDirection = model.Instances.New<IfcDirection>();
body.ExtrudedDirection.SetXYZ(0, 0, 1);
//parameters to insert the geometry in the model
var origin = model.Instances.New<IfcCartesianPoint>();
origin.SetXYZ(0, 0, 0);
body.Position = model.Instances.New<IfcAxis2Placement3D>();
body.Position.Location = origin;
//Create a Definition shape to hold the geometry
var shape = model.Instances.New<IfcShapeRepresentation>();
var modelContext = model.Instances.OfType<IfcGeometricRepresentationContext>().FirstOrDefault();
shape.ContextOfItems = modelContext;
shape.RepresentationType = "SweptSolid";
shape.RepresentationIdentifier = "Body";
shape.Items.Add(body);
//create visual style
model.Instances.New<IfcStyledItem> (styleItem => {
styleItem.Item = body;
styleItem.Styles.Add(model.Instances.New<IfcSurfaceStyle>(style => {
style.Side = IfcSurfaceSide.BOTH;
style.Styles.Add(model.Instances.New<IfcSurfaceStyleRendering>(rendering => {
rendering.SurfaceColour = model.Instances.New<IfcColourRgb>(colour => {
colour.Name = "Orange";
colour.Red = 1.0;
colour.Green = 0.5;
colour.Blue = 0.0;
});
}));
}));
});
//Create a Product Definition and add the model geometry to the wall
var rep = model.Instances.New<IfcProductDefinitionShape>();
rep.Representations.Add(shape);
wall.Representation = rep;
//now place the wall into the model
var lp = model.Instances.New<IfcLocalPlacement>();
var ax3D = model.Instances.New<IfcAxis2Placement3D>();
ax3D.Location = origin;
ax3D.RefDirection = model.Instances.New<IfcDirection>();
ax3D.RefDirection.SetXYZ(0, 1, 0);
ax3D.Axis = model.Instances.New<IfcDirection>();
ax3D.Axis.SetXYZ(0, 0, 1);
lp.RelativePlacement = ax3D;
wall.ObjectPlacement = lp;
// Where Clause: The IfcWallStandard relies on the provision of an IfcMaterialLayerSetUsage
var ifcMaterialLayerSetUsage = model.Instances.New<IfcMaterialLayerSetUsage>();
var ifcMaterialLayerSet = model.Instances.New<IfcMaterialLayerSet>();
var ifcMaterialLayer = model.Instances.New<IfcMaterialLayer>();
ifcMaterialLayer.LayerThickness = 10;
ifcMaterialLayerSet.MaterialLayers.Add(ifcMaterialLayer);
ifcMaterialLayerSetUsage.ForLayerSet = ifcMaterialLayerSet;
ifcMaterialLayerSetUsage.LayerSetDirection = IfcLayerSetDirectionEnum.AXIS2;
ifcMaterialLayerSetUsage.DirectionSense = IfcDirectionSenseEnum.NEGATIVE;
ifcMaterialLayerSetUsage.OffsetFromReferenceLine = 150;
// Add material to wall
var material = model.Instances.New<IfcMaterial>();
material.Name = "some material";
var ifcRelAssociatesMaterial = model.Instances.New<IfcRelAssociatesMaterial>();
ifcRelAssociatesMaterial.RelatingMaterial = material;
ifcRelAssociatesMaterial.RelatedObjects.Add(wall);
ifcRelAssociatesMaterial.RelatingMaterial = ifcMaterialLayerSetUsage;
// IfcPresentationLayerAssignment is required for CAD presentation in IfcWall or IfcWallStandardCase
var ifcPresentationLayerAssignment = model.Instances.New<IfcPresentationLayerAssignment>();
ifcPresentationLayerAssignment.Name = "some ifcPresentationLayerAssignment";
ifcPresentationLayerAssignment.AssignedItems.Add(shape);
// linear segment as IfcPolyline with two points is required for IfcWall
var ifcPolyline = model.Instances.New<IfcPolyline>();
var startPoint = model.Instances.New<IfcCartesianPoint>();
var midpoint = model.Instances.New<IfcCartesianPoint>();
var midpoint2 = model.Instances.New<IfcCartesianPoint>();
startPoint.SetXYZ(3000, 0, 1000);
midpoint.SetXYZ(3000, 2000, 1000);
midpoint2.SetXYZ(1000, 3000, 1000);
var endPoint = model.Instances.New<IfcCartesianPoint>();
endPoint.SetXYZ(0, 2000, 1000);
ifcPolyline.Points.Add(startPoint);
ifcPolyline.Points.Add(midpoint);
ifcPolyline.Points.Add(midpoint2);
ifcPolyline.Points.Add(endPoint);
var shape2D = model.Instances.New<IfcShapeRepresentation>();
shape2D.ContextOfItems = modelContext;
shape2D.RepresentationIdentifier = "Axis";
shape2D.RepresentationType = "Curve2D";
shape2D.Items.Add(ifcPolyline);
rep.Representations.Add(shape2D);
txn.Commit();
return wall;
}
}
This CreateWall function create Ifc wall. Please go throw it above code.

chartjs how to apply after animation

trying to extend a chart, so that i can draw lines up to the data point, but this is happening before the default animation. it would look smoother if it applied after.
i have got most of it to work.. but how do i get this to apply after chart animation.
var originalLineDraw = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
draw: function () {
originalLineDraw.apply(this, arguments);
var chart = this.chart;
var ctx = chart.chart.ctx;
var index = chart.config.data.lineAtIndex;
if (index) {
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-1']
var points = this.chart.getDatasetMeta(this.index).data;
for (var i = 0; i < points.length; i++) {
// var point_x = points[i]._model.x;
var point_y = points[i]._model.y;
ctx.beginPath();
ctx.setLineDash([5, 5]);/*dashes are 5px and spaces are 3px*/
ctx.moveTo(xaxis.getPixelForValue(undefined, i), point_y);
ctx.strokeStyle = '#fff';
ctx.lineTo(xaxis.getPixelForValue(undefined, i), yaxis.bottom);
ctx.stroke();
}
}
}
});
Update...
altho the darw is incorrect it still is playing after animation
var verticalLinePlugin = {
renderVerticalLine: function (chartInstance) {
var chart = chartInstance;
var ctx = chart.chart.ctx;
var maxpoint = [];
//loop the datasets
for (var y = 0; y < chart.config.data.datasets.length; y++) {
var dataset = chart.config.data.datasets[y];
if (dataset.hidden)
continue;
var points = chart.getDatasetMeta(y).data;
for (var i = 0; i < points.length; i++) {
var point_y = points[i]._model.y;
if (point_y < 0)
continue;
var point = maxpoint[i];
if (point == undefined) {
maxpoint.push({ id: i, y: point_y });
} else {
if (point.y > point_y) {
point.y = point_y;
}
}
}
}
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-1']
chart.data.datasets.forEach(function (dataset, i) {
var ds = dataset;
var meta = chart.getDatasetMeta(i);
meta.data.forEach(function (element, index) {
var value = maxpoint[i];
ctx.beginPath();
ctx.setLineDash([5, 5]);
ctx.moveTo(xaxis.getPixelForValue(undefined, i), value.y);
ctx.strokeStyle = '#fff';
ctx.lineTo(xaxis.getPixelForValue(undefined, i), yaxis.bottom);
ctx.stroke();
});
});
},
afterRender: function (chart) {
this.renderVerticalLine(chart);
}
};
Chart.plugins.register(verticalLinePlugin);
I made some small changes (non-intuitive!), and the vertical lines now appear after the animation.
Get the x values from the metadata instead of the data.
Either:
var x_point = element._model.x;
or:
var position = element.tooltipPosition();
var x_point = position.x;
Wrap the drawing in if(!hidden){}, then the vertical lines will disapear and reappear with the data. (The ternary assignment fixes a clash if the data starts hidden)
Do you need the value=max[i]? If just drawing the line up to the points, can get the y_point the same as for x.
var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-1'];
chart.data.datasets.forEach(function (dataset, i) {
var meta = chart.getDatasetMeta(i);
var hidden = (meta.hidden != undefined) ? meta.hidden : dataset.hidden
if(!hidden){
meta.data.forEach(function (element, index) {
//var value = maxpoint[i];
var x_point = element._model.x;
var y_point = element._model.y;
ctx.beginPath();
ctx.save();
ctx.setLineDash([5, 5])
ctx.strokeStyle = '#fff';
ctx.moveTo(x_point, y_point); // or value.y
ctx.lineTo(x_point, yaxis.bottom)
ctx.stroke();
ctx.restore();
});
}
});

How to create custom brush paint with fabric.js?

I have been trying to create a custom brush paint with an image file using fabric JS . I have tried using the fabric.PatternBrush but this is not the exact thing that I was looking for because this creates a background pattern kind of paint and what I am trying to do is repeat the image wherever the mouse is dragged.
Can anyone please direct me towards the right way? It will be fine for me to switch to any other drawing library that does what I am looking for.
I found a solution to this problem. We can create a custom brush using fabric.BaseBrush as follows:
fabric.SprayBrush = fabric.util.createClass(fabric.BaseBrush, {
opacity: .2,
width: 30,
_baseWidth: 5,
_drips: [],
_dripThreshold: 15,
_inkAmount: 0,
_interval: 20,
_lastPoint: null,
_point: null,
_strokeId: 0,
brush: null,
brushCol : '/static/img/creation_room/textures/texture2.png',
initialize: function(canvas, opt) {
var context = this;
opt = opt || {};
this.canvas = canvas;
this.width = opt.width || canvas.freeDrawingBrush.width;
this.opacity = opt.opacity || canvas.contextTop.globalAlpha;
this.color = opt.color || canvas.freeDrawingBrush.color;
this.canvas.contextTop.lineJoin = "round";
this.canvas.contextTop.lineCap = "round";
this._reset();
fabric.Image.fromURL(this.brushCol, function(brush) {
console.log(brush);
context.brush = brush;
context.brush.filters = [];
context.changeColor(context.color || this.color);
}, { crossOrigin: "anonymous" });
},
changeColor: function(color) {
this.color = color;
this.brush.filters[0] = new fabric.Image.filters.Tint({ color: color });
this.brush.applyFilters(this.canvas.renderAll.bind(this.canvas));
},
changeOpacity: function(value) {
this.opacity = value;
this.canvas.contextTop.globalAlpha = value;
},
onMouseDown: function(pointer) {
this._point = new fabric.Point(pointer.x, pointer.y);
this._lastPoint = this._point;
this.size = this.width + this._baseWidth;
this._strokeId = +new Date();
this._inkAmount = 0;
this.changeColor(this.color);
this._render();
},
onMouseMove: function(pointer) {
this._lastPoint = this._point;
this._point = new fabric.Point(pointer.x, pointer.y);
},
onMouseUp: function(pointer) {
},
_render: function() {
var context = this;
setTimeout(draw, this._interval);
function draw() {
var point, distance, angle, amount, x, y;
point = new fabric.Point(context._point.x || 0, context._point.y || 0);
distance = point.distanceFrom(context._lastPoint);
angle = point.angleBetween(context._lastPoint);
amount = (100 / context.size) / (Math.pow(distance, 2) + 1);
context._inkAmount += amount;
context._inkAmount = Math.max(context._inkAmount - distance / 10, 0);
if (context._inkAmount > context._dripThreshold) {
context._drips.push(new fabric.Drip(context.canvas.contextTop, point, context._inkAmount / 2, context.color, context._strokeId));
context._inkAmount = 0;
}
x = context._lastPoint.x + Math.sin(angle) - context.size / 2;
y = context._lastPoint.y + Math.cos(angle) - context.size / 2;
context.canvas.contextTop.drawImage(context.brush._element, x, y, context.size, context.size);
if (context.canvas._isCurrentlyDrawing) {
setTimeout(draw, context._interval);
} else {
context._reset();
}
}
},
_reset: function() {
this._drips.length = 0;
this._point = null;
this._lastPoint = null;
}
});
Now, we just need to use this brush in the canvas.
var canvas = new fabric.Canvas('canvas');
canvas.freeDrawingBrush = new fabric.SprayBrush(canvas, { width: 70,opacity: 0.6, color: "transparent" });

GenericSync event not initialising on view - Famo.us

I have a view (tribeProduct) that generates a list of surfaces that are contained in a scroll view, what I want to do is a create an event that when the view is "dragged" down, an animation comes into play. The following is what I have so far that for some reason isn't working.
for (var t = 0; t < tribesLength; t++) {
var tribe = new TribesView({tribes: tribes, tribe: t});
if(tribes[t]['notifications'] > 0) {
// Create view with list of surfaces contained in a scroll view
var tribeProduct = new ProductView({tribes: tribes, tribe: t});
var productModifier = new Modifier({
opacity: 0,
transform: Transform.translate(window.innerWidth * 1, 0, 100)
});
productContext.add(productModifier).add(tribeProduct);
tribe.on('click', function(e) {
var tribeProduct = this[0];
var productModifier = this[1];
productModifier.setOpacity(1, { duration: 500 });
productModifier.setTransform(Transform.translate(0, 0, 100), { duration: 500, curve: Easing.inOutBack });
var handleSwipe = new GenericSync(
['mouse', 'touch'],
{ direction: GenericSync.DIRECTION_Y }
);
tribeProduct.pipe(handleSwipe);
handleSwipe.on('end', (function(data) {
console.log('test');
var position = data.position;
var startPos = 100;
if(position > startPos) {
this
.setOpacity(
0, { duration: 500, curve: 'easeInOut' }
)
.setTransform(
Transform.translate(0, startPos + 200, 0), { duration: 500, curve: 'easeInOut' }
);
}
console.log(position);
}).bind(productModifier));
}.bind([tribeProduct, productModifier]));
}
tribe.pipe(scrollView);
surfaces.push(tribe);
}
I had a similar question it was targeted at a pull to refresh but it answers your questions as well. Or at least I believe it does.
Scrollview Pull to Refresh Famo.us
Using John Traver's response I came up with the refreshScrollView:
https://github.com/vizidrix/famous
If you look at the code I think it will help.

Raphael.js onmouseover onmouseout event

I've made 4 rectangles in raphael.js using the for loop. When I apply events such as onmouseover or onmouseout it applies only to the last rectangle created. I know something is wrong in my code. Please provide a solution and is there a way to simplify the code?
JS Fiddle Link
window.onload = function(){
var paper = Raphael(0,0,640,540);
for (i=0;i<2;i++){
for (j=0;j<2;j++){
var boxes = paper.rect(0+(j*320),0+(i*270),320,270).attr({fill:'#303030',stroke:'white'});
boxes.node.onmouseover = function () {
boxes.attr("fill", "blue");
};
boxes.node.onmouseout = function () {
boxes.attr("fill", "#303030");
};
}
}
}​
This is an extremely common mistake in javascript. You reuse the boxes variable, so when any of the handlers are executed, it points to the last value it had.
The common way of overcoming this is to wrap the code inside the loop in a function call:
window.onload = function() {
var paper = Raphael(0, 0, 640, 540);
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
(function(i, j) {
var boxes = paper.rect(0 + (j * 320), 0 + (i * 270), 320, 270).attr({
fill: '#303030',
stroke: 'white'
});
boxes.node.onmouseover = function() {
boxes.attr("fill", "blue");
};
boxes.node.onmouseout = function() {
boxes.attr("fill", "#303030");
};
})(i, j);
}
}
}
​