Why does my sprite disappear when I call shiftHSL? - phaser-framework

If I uncomment the shiftHSL line below, the sprite does not appear.
<script src='https://rawgit.com/photonstorm/phaser/master/build/phaser.js'></script>
<script>
var game = new Phaser.Game(800, 400, Phaser.AUTO, '', {
preload: function() { this.game.load.image('dwarf', 'res/dwarf.png') },
create: function() {
var bmd = game.make.bitmapData()
bmd.width = 80
bmd.height = 80
bmd.circle(bmd.width / 2, bmd.width / 2, bmd.width / 2, '#ffffff')
bmd.alphaMask('dwarf', bmd)
// bmd.shiftHSL(0, -.5, 0)
var sprite = game.add.sprite(100, 100, bmd)
}
});
</script>

Ok, I got it working. Looks like you need to call bmd.update() before calling shiftHSL.

Related

FabricJS Animate Path

I'm trying to smoothly animate a path in FabricJS. I've seen examples of how to animate lines, but nothing about animating paths.
I've been able to iterate through an array of path points to get something functioning, but it's choppy and doesn't work well:
function animateLine(pathArray) {
var pathString = '';
var directionLine;
pathArray.forEach((item, i) => {
setTimeout(() => {
pathString = pathString + item + ',';
canvas.remove(directionLine);
directionLine = new fabric.Path(pathString, {
fill: '',
stroke: 'black',
strokeDashArray: [5, 5],
objectCaching: false
});
canvas.add(directionLine);
}, i * 20);
});
}
animateLine(pathString);
Fiddle here.
I'm looking to do something like this example, but it uses Raphael and I'm hoping to not have to switch libraries.
Was able to figure out a solution with help from one of the mods pointing me to strokeDashOffset.
var canvas = new fabric.Canvas('c');
var pathArray = "M78.2,0.1c0,0,9.4,79.1,2.3,117 c-4.5,24.1-31.8,106.2-56.3,108.7c-12.7,1.3-24.2-11.9-16.5-15.5C15,207,40.2,231.1,19,261.7c-9.8,14.1-24.7,31.9-12.5,44.9 c11.3,12,53-36.8,59.2-23.8c8.6,18-40.8,23-28,49.2c14.7,30.4,21.6,39.9,48,58.5c31.3,22,147,66.2,147.2,149.5";
var path = new fabric.Path(pathArray, {
fill: '',
stroke: 'black',
strokeDashArray: [5, 5],
strokeDashOffset: 0
});
canvas.add(path);
function animatePath(path) {
path.animate('strokeDashOffset', '-=3', {
duration: 100,
onChange: canvas.renderAll.bind(canvas),
onComplete: function(){
animatePath(path)
}
});
}
animatePath(path);
Fiddle

How to add text via chart.renderer.text in Highcharts?

I have succeeded adding additional text to my charts, like here. This, I achieved through adding a "function(chart)" to my "var chart = new Highcharts.Chart"
$.get('xxx.csv', function(data)
{
var chart = new Highcharts.Chart({
...
plotOptions:
{
series:
{
....
}
}
}, function(chart)
{
chart.renderer.text('The dotted line represents ...', 100, 86)
.css({
fontSize: '13px',
color: '#666666'
})
.add();
}
)};
My current format is however different:
$(function () {
var options =
{
chart:
{
...
},
...
};
$.get('xxx.csv', function(data)
{
var series = {
data: []
};
var temp = []
// Split the lines
var lines = data.split('\n');
// For each line, split the record into seperate attributes
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if (lineNo !== 0) {
var xValue = +items[0],
kwh = parseFloat(items[2] / 1000);
if (!isNaN(kwh)) {
series.data.push({x:xValue,y: kwh, extra:items[1]});
}
}
});
// Push the completed series
options.series.push(series);
new Highcharts.Chart(options);
});
});
Now, I wonder how I can add a chart.renderer.text to the graph. I have tried different things, but didn't succeed. Where and how am I supposed to add the code for the text now? Here is a fiddle for this. Thanks for any hints!
You can add your text inside load event callback function of your chart. You can add this function inside your options - options.chart.events object.
http://api.highcharts.com/highcharts#chart.events.load
options.chart.events = {
load: function() {
var chart = this;
chart.renderer.text('The dotted line represents ...', 100, 186)
.css({
fontSize: '13px',
color: '#666666'
})
.add();
}
}
Here you can see an example how it can work:
http://jsfiddle.net/17ed42pa/1/
Best regards.

Matter.js doesn't update body properties if Pixi.js renderer is used

I want to update certain body properties if user clicks on it, e.g. body.render.lineWidth = 5;
It works just fine if the default canvas renderer is used. If I switch to Pixi.js renderer it stops working and doesn't seem to reflect any properties at all.
I also tried with the Matter.Body.set function but with no luck either. Properties are set actually to a body but the body keeps showing the initial style which was provided at the construction time.
What is the proper way to set those properties?
EDIT:
sample.js
var Engine = Matter.Engine,
World = Matter.World,
Bodies = Matter.Bodies,
Common = Matter.Common,
MouseConstraint = Matter.MouseConstraint;
var createOptions = function(options) {
var defaults = {
isManual: false,
sceneName: 'mixed',
sceneEvents: []
};
return Common.extend(defaults, options);
};
var options = {
positionIterations: 6,
velocityIterations: 4,
enableSleeping: false,
metrics: { extended: true },
render: {
controller: Matter.RenderPixi
}
};
var engine = Engine.create(document.getElementById('canvas-container'), createOptions(options));
var world = engine.world;
var mouseConstraint = MouseConstraint.create(engine, {
constraint: {
render: {
visible: false
}
}
});
World.add(engine.world, mouseConstraint);
World.add(world, [
Bodies.rectangle(400, 0, 800, 1, { isStatic: true }),
Bodies.rectangle(400, 600, 800, 1, { isStatic: true }),
Bodies.rectangle(800, 300, 1, 600, { isStatic: true }),
Bodies.rectangle(0, 300, 1, 600, { isStatic: true })
]);
var body = Bodies.polygon(200, 200, 4, Common.random(50, 60), {
isStatic: true,
friction: 1,
render: {
fillStyle: '#f0f0f0',
strokeStyle: 'black',
lineWidth: 1
}
});
World.add(world, body);
Matter.Events.on(mouseConstraint, 'mousedown', function(e) {
body.render.lineWidth = 5;
});
var renderOptions = engine.render.options;
renderOptions.wireframes = false;
renderOptions.hasBounds = false;
renderOptions.showDebug = false;
renderOptions.showBroadphase = false;
renderOptions.showBounds = false;
renderOptions.showVelocity = false;
renderOptions.showCollisions = false;
renderOptions.showAxes = false;
renderOptions.showPositions = false;
renderOptions.showAngleIndicator = false;
renderOptions.showIds = false;
renderOptions.showShadows = false;
renderOptions.showVertexNumbers = false;
renderOptions.showConvexHulls = false;
renderOptions.showInternalEdges = false;
renderOptions.showSeparations = false;
renderOptions.background = '#fff';
Engine.run(engine);
sample.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<div id="canvas-container"></div>
<script src="pixi.min.v3.0.10.js" type="text/javascript"></script>
<script src="matter.min.v0.9.1.js" type="text/javascript"></script>
<script src="sample.js" type="text/javascript"></script>
</body>
</html>
If I comment out controller: Matter.RenderPixi everything works OK.
RenderPixi creates primitives only once when the body first gets rendered and this gets cached.
To remove it from the cache, you should be able to do something like:
engine.render.primitives['b-' + body.id] = null;
Then it should get created again.

How to switch states in phaser frame work?

I am trying to switch to the Main Menu state in phaser through a function but couldn't get it to work. Below is my code snippet. The end function is called from the update function in game.js file.
end: function(){
player.kill();
ltext.setText("Over!!");
this.state.start('Menu');
},
You'd better not to call this function from the update function.
Instead, you can call it from a sprite or button event handler etc.
I tested game.state.start('xx') in update function and it worked as expected.
window.addEventListener('load', function(){
var game = new Phaser.Game(500, 190, Phaser.CANVAS, '', {
create : function (game) {
var textStyle = { font: "14px Arial", fill: "#ffcc00" };
game.add.text(60, 40, 'Phaser HTML5 Game Engine', textStyle);
game.add.text(60, 70, 'This is state 1', textStyle);
var textStyle = { font: "14px Arial", fill: "#00ff00"};
game.add.text(200, 130, 'Pointer here to enter state2', textStyle);
var graphics = game.add.graphics(0, 0);
graphics.beginFill(0x00ff00);
graphics.drawRect(200, 80, 50, 50);
graphics.endFill();
},
update : function (game) {
var x = game.input.x, y = game.input.y;
if(x > 200 && x < 250 && y > 80 && y < 130){
game.state.start('state2');
}
}
});
game.state.add('state2', {
create: function (game){
var textStyle = { font: "14px Arial", fill: "#00ff00"};
game.add.text(60, 40, 'Phaser HTML5 Game Engine', textStyle);
game.add.text(60, 70, 'Welcome to state 2', textStyle);
}
});
}, false);
body{text-align:center;margin:4px;padding:0;}
canvas{vertical-align:middle; background-color:#000;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.3.0/phaser.min.js"></script>

Save and Restore rectangles with connections in Draw2D.js touch via JSON

How do I create rectangles with 4 ports (each side) in a correct way, so I can save and restore them via JSON?
I tried this one, but only the rectangles are been saved. The connections and labels got lost.
JSFiddle: http://jsfiddle.net/xfvf4/36/
Create two elements (Add) - move them and connect them
Write: This gives the content as JSON-Array
Read: Should make the grafic out of the JSON-Array
The last point doesn't work.
JS:
var LabelRectangle = draw2d.shape.basic.Rectangle.extend({
NAME: "draw2d.shape.basic.Rectangle",
init: function (attr) {
this._super(attr);
this.label = new draw2d.shape.basic.Label({
text: "Text",
fontColor: "#0d0d0d",
stroke: 0
});
this.add(this.label, new draw2d.layout.locator.CenterLocator(this));
this.label.installEditor(new draw2d.ui.LabelInplaceEditor());
this.createPort("hybrid", new draw2d.layout.locator.BottomLocator(this));
},
getPersistentAttributes: function () {
var memento = this._super();
memento.labels = [];
var ports = [];
ports = this.getPorts();
memento.ports = [];
console.log(ports);
this.children.each(function (i, e) {
console.log(e);
memento.labels.push({
id: e.figure.getId(),
label: e.figure.getText(),
locator: e.locator.NAME
});
ports.each(function (i, e) {
memento.ports.push({
//id: e.id,
name: e.name,
locator: e.locator.NAME
});
});
});
return memento;
},
setPersistentAttributes: function (memento) {
this._super(memento);
this.resetChildren();
$.each(memento.labels, $.proxy(function (i, e) {
var label = new draw2d.shape.basic.Label(e.label);
var locator = eval("new " + e.locator + "()");
locator.setParent(this);
this.add(label, locator);
}, this));
}
});
$(window).load(function () {
var canvas = new draw2d.Canvas("gfx_holder");
$("#add").click(function (e) { // Add a new rectangle
var rect = new LabelRectangle({
width: 200,
height: 40,
radius: 3,
bgColor: '#ffffff',
stroke: 0
});
rect.createPort("hybrid", new draw2d.layout.locator.OutputPortLocator(rect));
rect.createPort("hybrid", new draw2d.layout.locator.InputPortLocator(rect));
rect.createPort("hybrid", new draw2d.layout.locator.TopLocator(rect));
canvas.add(rect, 150, 200);
});
$("#write").click(function (e) { // Write to pre-Element (JSON)
var writer = new draw2d.io.json.Writer();
writer.marshal(canvas, function(json){
$("#json").text(JSON.stringify(json,null,2));
$('#gfx_holder').empty();
});
});
$("#read").click(function (e) { // Read from pre-Element (JSON)
var canvas = new draw2d.Canvas("gfx_holder");
var jsonDocument = $('#json').text();
var reader = new draw2d.io.json.Reader();
reader.unmarshal(canvas, jsonDocument);
});
});
HTML:
<ul class="toolbar">
<li>Add</li>
<li>Write</li>
<li>Read</li>
</ul>
<div id="container" class="boxed">
<div onselectstart="javascript:/*IE8 hack*/return false" id="gfx_holder" style="width:100%; height:100%; ">
</div>
<pre id="json" style="overflow:auto;position:absolute; top:10px; right:10px; width:350; height:500;background:white;border:1px solid gray">
</pre>
</div>
Just use the write.js and Reader.js in the "json"-Folder of Draw2D.js 5.0.4 and this code:
$(window).load(function () {
var canvas = new draw2d.Canvas("gfx_holder");
// unmarshal the JSON document into the canvas
// (load)
var reader = new draw2d.io.json.Reader();
reader.unmarshal(canvas, jsonDocument);
// display the JSON document in the preview DIV
//
displayJSON(canvas);
// add an event listener to the Canvas for change notifications.
// We just dump the current canvas document into the DIV
//
canvas.getCommandStack().addEventListener(function(e){
if(e.isPostChangeEvent()){
displayJSON(canvas);
}
});
});
function displayJSON(canvas){
var writer = new draw2d.io.json.Writer();
writer.marshal(canvas,function(json){
$("#json").text(JSON.stringify(json, null, 2));
});
}
This should work:
var LabelRectangle = draw2d.shape.basic.Rectangle.extend({
NAME: "draw2d.shape.basic.Rectangle",
init: function (attr) {
this._super(attr);
this.label = new draw2d.shape.basic.Label({
text: "Text",
fontColor: "#0d0d0d",
stroke: 0
});
this.add(this.label, new draw2d.layout.locator.CenterLocator(this));
this.label.installEditor(new draw2d.ui.LabelInplaceEditor());
},
getPersistentAttributes: function () {
var memento = this._super();
memento.labels = [];
memento.ports = [];
this.getPorts().each(function(i,port){
memento.ports.push({
name : port.getName(),
port : port.NAME,
locator: port.getLocator().NAME
});
});
this.children.each(function (i, e) {
memento.labels.push({
id: e.figure.getId(),
label: e.figure.getText(),
locator: e.locator.NAME
});
});
return memento;
},
setPersistentAttributes: function (memento) {
this._super(memento);
this.resetChildren();
if(typeof memento.ports !=="undefined"){
this.resetPorts();
$.each(memento.ports, $.proxy(function(i,e){
var port = eval("new "+e.port+"()");
var locator = eval("new "+e.locator+"()");
this.add(port, locator);
port.setName(e.name);
},this));
}
$.each(memento.labels, $.proxy(function (i, e) {
var label = new draw2d.shape.basic.Label(e.label);
var locator = eval("new " + e.locator + "()");
locator.setParent(this);
this.add(label, locator);
}, this));
}
});

Resources