I am dynamically adding a rect element to crop/clip (using clipTo) a selected element,
It works perfect at the first time but when i add a second element to the canvas and begin to crop the second element the first element looses the crop/clip. Below is my code, there are 2 buttons 1 to start crop/clip (places a dynamic rect over the element to be cropped) second to do the cropping/clipping.
$('#crop').on('click', function (event) {
var left = el.left - object.left;
var top = el.top - object.top;
left *= 1;
top *= 1;
var width = el.width * 1;
var height = el.height * 1;
object.clipTo = function (ctx)
{
ctx.rect(-(el.width/2)+left, -(el.height/2)+top, parseInt(width*el.scaleX), parseInt(el.scaleY*height));
}
for(var i=0; i<$("#layers li").size();i++)
{
canvas.item(i).selectable= true;
}
disabled = true;
canvas.remove(canvas.getActiveObject());
lastActive = object;
canvas.renderAll();
});
$('#startCrop').on('click',function(){
canvas.remove(el);
if(canvas.getActiveObject())
{
object=canvas.getActiveObject();
if (lastActive && lastActive !== object) {
lastActive.clipTo = null;
}
el = new fabric.Rect
({
fill: 'rgba(0,0,0,0.3)',
originX: 'left',
originY: 'top',
stroke: '#ccc',
strokeDashArray: [2, 2],
opacity: 1,
width: 1,
height: 1,
borderColor: '#36fd00',
cornerColor: 'green',
hasRotatingPoint:false
});
el.left=canvas.getActiveObject().left;
selection_object_left=canvas.getActiveObject().left;
selection_object_top=canvas.getActiveObject().top;
el.top=canvas.getActiveObject().top;
el.width=canvas.getActiveObject().width*canvas.getActiveObject().scaleX;
el.height=canvas.getActiveObject().height*canvas.getActiveObject().scaleY;
canvas.add(el);
canvas.setActiveObject(el);
for(var i=0; i<$("#layers li").size();i++)
{
canvas.item(i).selectable= false;
}
}
else{
alert("Please select an object or layer");
}
});
Is this what you're looking for? http://jsfiddle.net/86bTc/4/
You set the lastActive.clipTo = null;
try this code
function crop()
{
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
}
else {
var obj = canvas.getActiveObject();
fabric.Image.fromURL(canvas.toDataURL({
format: 'png',
left: obj.left + 1,
top: obj.top + 1,
width: obj.width * obj.scaleX,
height: obj.height * obj.scaleY,
}), function (img) {
canvas.remove(obj);
canvas.remove(ao);
canvas.add(img);
canvas.renderAll();
})
}
}
;
function Select() {
ao = canvas.getActiveObject();
if (!ao)
return;
canvas.bringToFront(ao);
ao.selectable = false;
canvas.add(new fabric.Rect({
left: 200,
top: 200,
width: 200,
height: 200,
fill: 'transparent',
stroke: '#000000',
hasRotatingPoint: false,
strokeDashArray: [5, 5],
cornerSize: 8,
}));
}
Related
Is there any way to do the same with the cropbox action in the link below?
I am using the latest version of konva, but it seems that the link does not work after version 4.
https://codepen.io/kade87/pen/vYavQMp?editors=1011
How can I use it to work like a link in the latest version?
We must solve this problem. Or is there a javascript crop library that supports both pc and mobile? If so, please recommend. However, most of the libraries didn't work the way we wanted.
<script src="https://unpkg.com/konva#^4/konva.min.js"></script>
<div id="container"></div>
<script>
// noprotect
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight
});
const layer = new Konva.Layer();
stage.add(layer);
Konva.Image.fromURL('https://i.imgur.com/ktWThtZ.png', img => {
img.setAttrs({
width: stage.width(),
height: stage.height(),
opacity: 0.5
});
layer.add(img)
})
Konva.Image.fromURL('https://i.imgur.com/ktWThtZ.png', img => {
var group = new Konva.Group({
clipFunc: (ctx) => {
ctx.save();
ctx.translate(fakeShape.x(), fakeShape.y())
ctx.rotate(Konva.getAngle(fakeShape.rotation()))
ctx.rect(0, 0, fakeShape.width() * fakeShape.scaleX(), fakeShape.height() * fakeShape.scaleY());
ctx.restore()
}
})
layer.add(group);
img.setAttrs({
width: stage.width(),
height: stage.height(),
});
group.add(img);
var fakeShape = new Konva.Rect({
width: 100,
height: 100,
x: 100,
y: 100,
fill: 'rgba(0,0,0,0)',
draggable: true
})
layer.add(fakeShape);
var tr = new Konva.Transformer({
enabledAnchors: ['top-left', 'bottom-right'],
rotateEnabled: false,
keepRatio: false,
flipEnabled: true,
node: fakeShape,
boundBoxFunc: (oldBox, newBox) => {
if(newBox.width < 50) {
newBox.width = 50
// newBox.x = oldBox.x
}
if(newBox.height < 50) {
newBox.height = 50
// newBox.y = oldBox.y
}
return newBox
}
});
layer.add(tr);
layer.draw();
});
</script>
I have a problem that I can't solve. I want to use JointJS fromJSON function to reconstruct the flowchart from a JSON (previously exported using JoinJS's toJSON function.
The problem is that the call to the fromJSON function always returns the following error:
Whether I call it inside the hook mounted () or call it from the click of a button.
For completeness I also want to say that I am using Vue.js.
The code I'm using instead is the following:
<template>
<div class="wrapper">
<button v-on:click="getGraphJSON">Get graph JSON</button>
<button v-on:click="resetGraphJSON">Restore graph from JSON</button>
<div id="myholder"></div>
</div>
</template>
<script>
const _ = require('lodash')
const joint = require('jointjs')
const g = require('../../node_modules/jointjs/dist/geometry.js')
const backbone = require('../../node_modules/backbone/backbone.js')
const $ = require('../../node_modules/jquery/dist/jquery.js')
import '../../node_modules/jointjs/dist/joint.css';
var CustomRectangle = joint.shapes.standard.Rectangle.define('CustomRectangle', {
type: 'CustomRectangle',
attrs: {
body: {
rx: 10, // add a corner radius
ry: 10,
strokeWidth: 1,
fill: 'cornflowerblue'
},
label: {
textAnchor: 'left', // align text to left
refX: 10, // offset text from right edge of model bbox
fill: 'white',
fontSize: 18
}
}
}, {
markup: [{
tagName: 'rect',
selector: 'body',
}, {
tagName: 'text',
selector: 'label'
}]
}, {
createRandom: function() {
var rectangle = new this();
var fill = '#' + ('000000' + Math.floor(Math.random() * 16777215).toString(16)).slice(-6);
var stroke = '#' + ('000000' + Math.floor(Math.random() * 16777215).toString(16)).slice(-6);
var strokeWidth = Math.floor(Math.random() * 6);
var strokeDasharray = Math.floor(Math.random() * 6) + ' ' + Math.floor(Math.random() * 6);
var radius = Math.floor(Math.random() * 21);
rectangle.attr({
body: {
fill: fill,
stroke: stroke,
strokeWidth: strokeWidth,
strokeDasharray: strokeDasharray,
rx: radius,
ry: radius
},
label: { // ensure visibility on dark backgrounds
fill: 'black',
stroke: 'white',
strokeWidth: 1,
fontWeight: 'bold'
}
});
return rectangle;
}
});
export default {
name: 'JointChartRestorable',
data() {
return {
graph: null,
paper: null,
// graphJSON: JSON.parse('{"cells":[{"type":"standard.Rectangle","position":{"x":100,"y":30},"size":{"width":100,"height":40},"angle":0,"id":"049776c9-7b6d-4aaa-8b02-1edc3bea9852","z":1,"attrs":{"body":{"fill":"blue"},"label":{"fill":"white","text":"Rect #1"}}},{"type":"standard.Rectangle","position":{"x":400,"y":30},"size":{"width":100,"height":40},"angle":0,"id":"b6e77973-1195-4749-99e1-728549329b11","z":2,"attrs":{"body":{"fill":"#2C3E50","rx":5,"ry":5},"label":{"fontSize":18,"fill":"#3498DB","text":"Rect #2","fontWeight":"bold","fontVariant":"small-caps"}}},{"type":"standard.Link","source":{"id":"049776c9-7b6d-4aaa-8b02-1edc3bea9852"},"target":{"id":"b6e77973-1195-4749-99e1-728549329b11"},"id":"4ed8e3b3-55de-4ad2-b79e-d4848adc4a58","labels":[{"attrs":{"text":{"text":"Hello, World!"}}}],"z":3,"attrs":{"line":{"stroke":"blue","strokeWidth":1,"targetMarker":{"d":"M 10 -5 0 0 10 5 Z","stroke":"black","fill":"yellow"},"sourceMarker":{"type":"path","stroke":"black","fill":"red","d":"M 10 -5 0 0 10 5 Z"}}}}],"graphCustomProperty":true,"graphExportTime":1563951791966}')
// graphJSON: JSON.parse('{"cells":[{"type":"examples.CustomRectangle","position":{"x":90,"y":30},"size":{"width":100,"height":40},"angle":0,"id":"faa7f957-4691-4bb2-b907-b2054f7e07de","z":1,"attrs":{"body":{"fill":"blue"},"label":{"text":"Rect #1"}}}]}')
graphJSON: JSON.parse('{"cells":[{"type":"CustomRectangle","position":{"x":100,"y":30},"size":{"width":100,"height":40},"angle":0,"id":"f02da591-c03c-479f-88cf-55c291064ca8","z":1,"attrs":{"body":{"fill":"blue"},"label":{"text":"Rect #1"}}}]}')
};
},
methods: {
getGraphJSON: function() {
this.graphJSON = this.graph.toJSON();
console.log(JSON.stringify(this.graphJSON));
this.graph.get('graphCustomProperty'); // true
this.graph.get('graphExportTime');
},
resetGraphJSON: function() {
if(this.graphJSON !== undefined && this.graphJSON !== null && this.graphJSON !== '') {
this.graph.fromJSON(this.graphJSON);
// this.paper.model.set(this.graphJSON);
} else {
alert('Devi prima cliccare sul tasto "Get graph JSON" almeno una volta');
}
}
},
mounted() {
this.graph = new joint.dia.Graph();
this.graph.fromJSON(this.graphJSON);
// this.graph.set('graphCustomProperty', true);
// this.graph.set('graphExportTime', Date.now());
this.paper = new joint.dia.Paper({
el: document.getElementById('myholder'),
model: this.graph,
width: '100%',
height: 600,
gridSize: 10,
drawGrid: true,
background: {
color: 'rgba(0, 255, 0, 0.3)'
},
// interactive: false, // disable default interaction (e.g. dragging)
/*elementView: joint.dia.ElementView.extend({
pointerdblclick: function(evt, x, y) {
joint.dia.CellView.prototype.pointerdblclick.apply(this, arguments);
this.notify('element:pointerdblclick', evt, x, y);
this.model.remove();
}
}),
linkView: joint.dia.LinkView.extend({
pointerdblclick: function(evt, x, y) {
joint.dia.CellView.prototype.pointerdblclick.apply(this, arguments);
this.notify('link:pointerdblclick', evt, x, y);
this.model.remove();
}
})*/
});
/*this.paper.on('cell:pointerdblclick', function(cellView) {
var isElement = cellView.model.isElement();
var message = (isElement ? 'Element' : 'Link') + ' removed';
eventOutputLink.attr('label/text', message);
eventOutputLink.attr('body/visibility', 'visible');
eventOutputLink.attr('label/visibility', 'visible');
});*/
/***************************************************/
/************** GRAPH ELEMENT SAMPLE ***************/
/***************************************************/
// var rect = new joint.shapes.standard.Rectangle();
// var rect = new CustomRectangle();
// rect.position(100, 30);
// rect.resize(100, 40);
// rect.attr({
// body: {
// fill: 'blue'
// },
// label: {
// text: 'Rect #1',
// fill: 'white'
// }
// });
// rect.addTo(this.graph);
/***************************************************/
/************** GRAPH ELEMENT SAMPLE ***************/
/***************************************************/
}
}
</script>
Right now I'm using a custom element, previously defined, but I've also done tests using the standard Rectangle element of JointJS.
Can anyone tell me if I'm doing something wrong?
Many thanks in advance.
Markup object could not be found in element that's reason why this error is getting. After it's imported jointjs to the vueJS project through jointjs or rabbit dependency;
import * as joint from 'jointjs' or import * as joint from 'rabbit'
window.joint = joint;
joint should be adjusted as global in environment by using window.
I tried to align an object within a group. When I align the first object to the left, center or right it was successful, then I tried for the second object, the first object moved by itself!
Please see the image below (GIF):
Fabric JS Object Alignment
I used HTML5 Canvas, fabric JS & jQuery for the development.
Here is the fiddle: https://jsfiddle.net/mt0ccqq2/
Here is the Code:
$(document).ready(function() {
var canvas = new fabric.Canvas("canvas", { preserveObjectStacking: true });
// create rectangle
var rect = new fabric.Rect({
left: 50,
top: 50,
width: 300,
height: 100,
fill: '#ff0000'
});
// create circle
var text = new fabric.Text("Align Me next", {
left: 190,
top: 320,
fontSize: 20
});
// create text
var text2 = new fabric.Text("Align me first", {
left: 100,
top: 200,
fontSize: 20
});
canvas.add(rect, text, text2);
canvas.renderAll();
// GROUP ON SELECTION
canvas.on("selection:created", function(e) {
var activeObj = canvas.getActiveGroup();
if(activeObj.type === "group") {
console.log("Group created");
var groupWidth = e.target.getWidth();
var groupHeight = e.target.getHeight();
e.target.forEachObject(function(obj) {
var itemWidth = obj.getBoundingRect().width;
var itemHeight = obj.getBoundingRect().height;
// ================================
// OBJECT ALIGNMENT: " H-LEFT "
// ================================
$('#objAlignLeft').click(function() {
obj.set({
left: -(groupWidth / 2),
originX: 'left'
});
obj.setCoords();
canvas.renderAll();
});
// ================================
// OBJECT ALIGNMENT: " H-CENTER "
// ================================
$('#objAlignCenter').click(function() {
obj.set({
left: (0 - itemWidth/2),
originX: 'left'
});
obj.setCoords();
canvas.renderAll();
});
// ================================
// OBJECT ALIGNMENT: " H-RIGHT "
// ================================
$('#objAlignRight').click(function() {
obj.set({
left: (groupWidth/2 - itemWidth/2),
originX: 'center'
});
obj.setCoords();
canvas.renderAll();
});
});
}
}); // END OF " SELECTION:CREATED "
});
Any help would be appreciated. Thanks in advance.
I think this is what you're looking for, right?
Here's the tweak to your code...
canvas.on("selection:cleared", function(e) {
$('#objAlignLeft').off('click');
$('#objAlignCenter').off('click');
$('#objAlignRight').off('click');
});
And here's the all important JSFiddle, https://jsfiddle.net/rekrah/xxrqbhph/.
Let me know if you have any further questions. Happy to help!
I need some help with my code. I want to make the str sprite invisible after 10 seconds.
I'm using this link for help: http://phaser.io/examples/v2/time/basic-timed-event
var game = new Phaser.Game(500, 550, Phaser.AUTO);
//var picture;
var Pacman = function (game) {
this.map = null;
this.layer = null;
this.pacman = null;
this.safetile = 14;
this.gridsize = 16;
this.speed = 100;
this.threshold = 3;
this.turnSpeed = 200;
this.marker = new Phaser.Point();
this.turnPoint = new Phaser.Point();
this.directions = [ null, null, null, null, null ];
this.opposites = [ Phaser.NONE, Phaser.RIGHT, Phaser.LEFT, Phaser.DOWN, Phaser.UP ];
this.current = Phaser.NONE;
this.turning = Phaser.NONE;
this.score=0;
this.scoreText='';
this.bonus=0;
this.bonusText='';
};
Pacman.prototype = {
init: function () {
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
Phaser.Canvas.setImageRenderingCrisp(this.game.canvas);
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
// We need this because the assets are on github pages
// Remove the next 2 lines if running locally
this.load.baseURL = 'https://nikosdaskalos.github.io/pacman/';
this.load.crossOrigin = 'anonymous';
this.load.image('str', 'assets/str.png');
this.load.image('dot', 'assets/dot.jpg');
this.load.image('coin', 'assets/coin.jpg');
this.load.image('tiles', 'assets/pacman-tiles.png');
this.load.spritesheet('pacman', 'assets/pacman.png');
this.load.tilemap('map', 'assets/pacman-map.json', null, Phaser.Tilemap.TILED_JSON);
// Needless to say, graphics (C)opyright Namco
},
create: function () {
this.map = this.add.tilemap('map');
this.map.addTilesetImage('pacman-tiles', 'tiles');
this.layer = this.map.createLayer('Pacman');
//picture = game.add.sprite(game.world.centerX, game.world.centerY, 'str');
//picture.anchor.setTo(0.5, 0.5);
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
this.dots = this.add.physicsGroup();
this.map.createFromTiles(36, this.safetile, 'str', this.layer, this.dots);
this.map.createFromTiles(7, this.safetile, 'dot', this.layer, this.dots);
this.map.createFromTiles(35, this.safetile, 'coin', this.layer, this.dots);
// The dots will need to be offset by 6px to put them back in the middle of the grid
this.dots.setAll('x', 6, false, false, 1);
this.dots.setAll('y', 6, false, false, 1);
// Pacman should collide with everything except the safe tile
this.map.setCollisionByExclusion([this.safetile], true, this.layer);
// Position Pacman at grid location 14x17 (the +8 accounts for his anchor)
this.pacman = this.add.sprite((14 * 16) + 8, (17 * 16) + 8, 'pacman', 0);
this.pacman.anchor.set(0.5);
//this.pacman.animations.add('munch', [0, 1, 2, 1], 20, true);
this.physics.arcade.enable(this.pacman);
this.pacman.body.setSize(16, 16, 0, 0);
this.cursors = this.input.keyboard.createCursorKeys();
//this.pacman.play('munch');
this.move(Phaser.LEFT);
this.scoreText = game.add.text(0, 500, 'Score: 0', { fontSize: '34px Arial', fill: 'white' });
lives = game.add.group();
game.add.text(game.world.width - 340, 500, 'Lives : ', { fontSize: '34px Arial', fill: 'white' });
this.bonusText = game.add.text(360, 500, 'Bonus: 0', { fontSize: '20px Arial', fill: 'white' });
for (var i = 0; i < 3; i++)
{
var pacman = lives.create(game.world.width - 235 + (30 * i), 517, 'pacman');
pacman.anchor.setTo(0.5, 0.5);
pacman.angle = 90;
pacman.alpha = 0.4;
}
},
//function fadePicture() {
//game.add.tween(picture).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
//},
checkKeys: function () {
if (this.cursors.left.isDown && this.current !== Phaser.LEFT)
{
this.checkDirection(Phaser.LEFT);
}
else if (this.cursors.right.isDown && this.current !== Phaser.RIGHT)
{
this.checkDirection(Phaser.RIGHT);
}
else if (this.cursors.up.isDown && this.current !== Phaser.UP)
{
this.checkDirection(Phaser.UP);
}
else if (this.cursors.down.isDown && this.current !== Phaser.DOWN)
{
this.checkDirection(Phaser.DOWN);
}
else
{
// This forces them to hold the key down to turn the corner
this.turning = Phaser.NONE;
}
},
checkDirection: function (turnTo) {
if (this.turning === turnTo || this.directions[turnTo] === null || this.directions[turnTo].index !== this.safetile)
{
// Invalid direction if they're already set to turn that way
// Or there is no tile there, or the tile isn't index 1 (a floor tile)
return;
}
// Check if they want to turn around and can
if (this.current === this.opposites[turnTo])
{
this.move(turnTo);
}
else
{
this.turning = turnTo;
this.turnPoint.x = (this.marker.x * this.gridsize) + (this.gridsize / 2);
this.turnPoint.y = (this.marker.y * this.gridsize) + (this.gridsize / 2);
}
},
turn: function () {
var cx = Math.floor(this.pacman.x);
var cy = Math.floor(this.pacman.y);
// This needs a threshold, because at high speeds you can't turn because the coordinates skip past
if (!this.math.fuzzyEqual(cx, this.turnPoint.x, this.threshold) || !this.math.fuzzyEqual(cy, this.turnPoint.y, this.threshold))
{
return false;
}
// Grid align before turning
this.pacman.x = this.turnPoint.x;
this.pacman.y = this.turnPoint.y;
this.pacman.body.reset(this.turnPoint.x, this.turnPoint.y);
this.move(this.turning);
this.turning = Phaser.NONE;
return true;
},
move: function (direction) {
var speed = this.speed;
if (direction === Phaser.LEFT || direction === Phaser.UP)
{
speed = -speed;
}
if (direction === Phaser.LEFT || direction === Phaser.RIGHT)
{
this.pacman.body.velocity.x = speed;
}
else
{
this.pacman.body.velocity.y = speed;
}
// Reset the scale and angle (Pacman is facing to the right in the sprite sheet)
/* this.pacman.scale.x = 1;
this.pacman.angle = 0;
if (direction === Phaser.LEFT)
{
this.pacman.scale.x = -1;
}
else if (direction === Phaser.UP)
{
this.pacman.angle = 270;
}
else if (direction === Phaser.DOWN)
{
this.pacman.angle = 90;
}
this.current = direction;
},*/
this.add.tween(this.pacman).to( { angle: this.getAngle(direction) }, this.turnSpeed, "Linear", true);
this.current = direction;
},
getAngle: function (to) {
// About-face?
if (this.current === this.opposites[to])
{
return "180";
}
if ((this.current === Phaser.UP && to === Phaser.LEFT) ||
(this.current === Phaser.DOWN && to === Phaser.RIGHT) ||
(this.current === Phaser.LEFT && to === Phaser.DOWN) ||
(this.current === Phaser.RIGHT && to === Phaser.UP))
{
return "-90";
}
return "90";
},
eatDot: function (pacman, dot) {
dot.kill();
var audio = new Audio('assets/pacman_chomp.wav');
audio.play()
this.score+=10;
this.scoreText.text= 'Score: ' + this.score;
//setTimeout(audio.play(),2000);
if (this.dots.total === 0)
{
this.dots.callAll('revive');
}
},
/*function muteAudio() {
var audio = document.getElementById('audioPlayer');
if (audio.mute = false) {
document.getElementById('audioPlayer').muted = true;
}
else {
audio.mute = true
document.getElementById('audioPlayer').muted = false;
}
}*/
eatCoin: function(pacman,coin){//pente
coin.kill();
this.score+=20;
this.scoreText.text= 'Score: ' + this.score;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.coins.total===0)
{
this.coins.callAll('revive');
}
},
eatStr: function(pacman,str){//pente
str.kill();
this.bonus+=100;
this.bonusText.text= 'Bonus: ' + this.bonus;
var audio = new Audio('assets/pacman_eatfruit.wav');
audio.play()
if(this.strs.total===0)
{
this.strs.callAll('revive');
}
},
update: function () {
this.physics.arcade.collide(this.pacman, this.layer);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatDot, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatCoin, null, this);
this.physics.arcade.overlap(this.pacman, this.dots, this.eatStr, null, this);
this.marker.x = this.math.snapToFloor(Math.floor(this.pacman.x), this.gridsize) / this.gridsize;
this.marker.y = this.math.snapToFloor(Math.floor(this.pacman.y), this.gridsize) / this.gridsize;
// Update our grid sensors
this.directions[1] = this.map.getTileLeft(this.layer.index, this.marker.x, this.marker.y);
this.directions[2] = this.map.getTileRight(this.layer.index, this.marker.x, this.marker.y);
this.directions[3] = this.map.getTileAbove(this.layer.index, this.marker.x, this.marker.y);
this.directions[4] = this.map.getTileBelow(this.layer.index, this.marker.x, this.marker.y);
this.checkKeys();
if (this.turning !== Phaser.NONE)
{
this.turn();
}
}
};
game.state.add('Game', Pacman, true);
</script>
</body>
</html>
So, can anyone help me with making the str invisible after 10 seconds?
You were pretty close.
I'm going to use pacman as an example, since I'm not 100% sure how you were going to fade out the coins. When Pacman eats them?
First, you want the following fadePicture function:
fadePicture: function() {
game.add.tween(this.pacman).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true);
},
Note how that was changed from function fadePicture().
Next, in your create function you can refer to it:
this.game.time.events.add(Phaser.Timer.SECOND * 4, this.fadePicture, this);
That replaces the following:
//game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this);
I've created a JSFiddle with the relevant changes.
If you do want your coins to fade then I would try updating fadePicture to accept a dot/str parameter and then game.add.tween on that.
What's wrong with loading this JSON?
Select a new object, set its ID, add and save it. Trying to reload the JSON object results in an empty canvas.
http://jsfiddle.net/Sugv4/14/
function loadCanvas() {
canvas.clear();
window.alert(js);
canvas.loadFromDatalessJSON(js)
canvas.renderAll();
}
Try put this in Javascript code:
var canvas;
$(function () {
canvas = window._canvas = new fabric.Canvas('c');
fabric.Labeledrect = fabric.util.createClass(fabric.Rect, {
type: 'labeledRect',
initialize: function (options) {
options || (options = {});
this.callSuper('initialize', options);
this.set('label', options.label);
this.set('id', options.id);
},
toObject: function () {
return fabric.util.object.extend(this.callSuper('toObject'), {
label: this.get('label'),
id: this.get('id')
});
},
_render: function (ctx) {
this.callSuper('_render', ctx);
ctx.font = '10px Helvetica';
ctx.fillStyle = '#333';
ctx.fillText(this.label, -this.width / 2, -this.height / 2 + 10);
ctx.fillText(this.id, -this.width / 2, -this.height / 2 + 30);
}
});
fabric.Labeledrect.fromObject = function (object, callback) {
return new fabric.Labeledrect(object);
}
fabric.Labeledrect.async = true;
});
function voegObjectToe() {
var myObjects = document.getElementById("myObjects");
var kenmerk = myObjects.options[myObjects.selectedIndex].text;
//nieuw object
var rect = new fabric.Labeledrect({
left: canvas.width / 2,
top: canvas.height / 2
});
if (kenmerk == 'Camper') {
rect.set({
width: 80,
height: 50,
fill: '#faa',
label: 'Camper',
id: document.getElementById("myObject").value
});
} else if (kenmerk == 'Caravan') {
rect.set({
width: 80,
height: 60,
fill: '#3ac',
label: 'Caravan',
id: document.getElementById("myObject").value
});
} else if (kenmerk == 'Auto') {
rect.set({
width: 70,
height: 40,
fill: '#bbb',
label: 'Auto',
id: document.getElementById("myObject").value
});
} else if (kenmerk == "Boot") {
rect.set({
width: 150,
height: 60,
fill: '#8d1',
label: 'Boot',
id: document.getElementById("myObject").value
});
}
canvas.add(rect);
rect.set({
label: kenmerk + ' ' + rect.width * 7 + ' cm',
rx: 8,
ry: 8
});
canvas.renderAll();
}
function saveCanvas() {
js = JSON.stringify(canvas.toDatalessJSON());
}
function loadCanvas() {
//window.alert(js);
canvas.clear();
canvas.loadFromDatalessJSON(js);
canvas.renderAll();
}