HTML Canvas Clears and Reappears - html

I have a html canvas that I draw a rect on, when I clear the canvas the screen clears but when you move the mouse the rect reappears. I stretch the rect vertically. Here is a code pen example of what is happening, you have to double click on the canvas for the rect to appear. https://codepen.io/tjquinn/pen/BYZQqo
HTML
<div id="app">
<div class="cv">
<canvas v-on:mousedown="mouseDown" v-on:mousemove="mouseMove" v-on:mouseup="mouseUp" #dblclick="dclick" id="rect" class="rect" width="150" height="700"></canvas>
<button v-on:click="clear">
Clear
</button>
</div>
</div>
JS
methods: {
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
getVal: function (x) {
this.canvas2 = document.getElementById('rect');
this.ctx2 = this.canvas2.getContext('2d');
this.st = this.canvas2.height;
this.ic = (this.st / x);
},
draw: function () {
this.ctx2.fillStyle = "#222222";
this.ctx2.fillRect(this.ctx2.rect.startX, this.ctx2.rect.startY, this.ctx2.rect.w, this.ctx2.rect.h);
this.drawHandles();
},
drawHandles: function () {
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY, this.closeEnough); //top left corner
//drawCircle(rect.startX + rect.w, rect.startY, closeEnough);
//drawCircle(rect.startX + rect.w, rect.startY + rect.h, closeEnough);
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY + this.ctx2.rect.h, this.closeEnough);
},
drawCircle: function (x, y, radius) {
this.ctx2.fillStyle = "#FF0000";
this.ctx2.beginPath();
this.ctx2.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx2.closePath();
this.ctx2.fill();
},
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
mouseDown: function (event) {
this.mouseX = event.pageX - this.canvas2.offsetLeft;
this.mouseY = event.pageY - this.canvas2.offsetTop;
// if there isn't a rect yet
if (this.ctx2.rect.w === undefined) {
this.ctx2.rect.startX = this.mouseY;
this.ctx2.rect.startY = this.mouseX;
this.dragBR = true;
}
if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY)) {
this.dragTL = true;
}
else if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY + this.ctx2.rect.h)) {
this.dragBR = true;
}
else {
// handle not resizing
}
this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height);
this.draw();
},
mouseMove: function (event) {
this.mouseX = event.pageX - this.canvas2.offsetLeft;
this.mouseY = event.pageY - this.canvas2.offsetTop;
if (this.dragTL) {
//rect.w += rect.startX - mouseX;
this.ctx2.rect.h += this.ctx2.rect.startY - this.mouseY;
//rect.startX = mouseX;
this.ctx2.rect.startY = this.mouseY;
}
else if (this.dragBR) {
//rect.w = Math.abs(rect.startX - mouseX);
this.ctx2.rect.h = Math.abs(this.ctx2.rect.startY - this.mouseY);
}
this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height);
this.draw();
},
mouseUp: function () {
this.dragTL = false;
this.dragTR = false;
this.dragBL = false;
this.dragBR = false;
},
dclick: function (e) {
console.log("Fires");
e.preventDefault();
this.ctx2.rect = {
startX: 25,
startY: 100,
w: (this.canvas2.width - 50),
h: 300,
}
this.draw();
this. ln = this.lines;
this.getVal(10);
},
clear: function () {
this.cv2 = 'rect';
this.canvas2 = document.getElementById(this.cv2);
this.ctx2 = this.canvas2.getContext('2d');
console.log(this.ctx2.clearRect(0, 0, this.canvas2.width, this.canvas2.height));
console.log("Clear should run");
},
}
})

It turns out the error was in my logic that was pointed out by Kamal Singh, I needed to add clear flags to my methods so that they do not run if the screen has been cleared.
<html>
<head>
<title>Test</title>
<script src="vue.min.js"></script>
</head>
<body>
<div id="app">
<div class="cv">
<canvas style='border:1px solid;' v-on:mousedown="mouseDown" v-on:mousemove="mouseMove" v-on:mouseup="mouseUp" #dblclick="dclick" id="rect" class="rect" width="150" height="700"></canvas>
<button v-on:click="clear">
Clear
</button>
</div>
</div>
<script>
new Vue({
el: '#app',
data: function() {
return {
rect : {},
drag : false,
closeEnough : 10,
st : 0,
ic : 0,
mouseX : 0,
mouseY : 0,
dragTL : false,
dragBL : false,
dragTR : false,
dragBR : false,
cv2: '',
ln: 0,
cleared: true
}
},
mounted: function () {
this.getVal(10);
this.draw();
},
methods: {
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
getVal: function (x) {
this.canvas2 = document.getElementById('rect');
this.ctx2 = this.canvas2.getContext('2d');
this.st = this.canvas2.height;
this.ic = (this.st / x);
},
draw: function () {
this.ctx2.fillStyle = "#222222";
this.ctx2.fillRect(this.ctx2.rect.startX, this.ctx2.rect.startY, this.ctx2.rect.w, this.ctx2.rect.h);
this.drawHandles();
},
drawHandles: function () {
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY, this.closeEnough); //top left corner
//drawCircle(rect.startX + rect.w, rect.startY, closeEnough);
//drawCircle(rect.startX + rect.w, rect.startY + rect.h, closeEnough);
this.drawCircle(this.ctx2.rect.startX + this.ctx2.rect.w/2, this.ctx2.rect.startY + this.ctx2.rect.h, this.closeEnough);
},
drawCircle: function (x, y, radius) {
this.ctx2.fillStyle = "#FF0000";
this.ctx2.beginPath();
this.ctx2.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx2.closePath();
this.ctx2.fill();
},
checkCloseEnough: function (p1, p2) {
return Math.abs(p1 - p2) < this.closeEnough;
},
mouseDown: function (event) {
if(this.cleared) return;
this.mouseX = event.pageX - this.canvas2.offsetLeft;
this.mouseY = event.pageY - this.canvas2.offsetTop;
// if there isn't a rect yet
if (this.ctx2.rect.w === undefined) {
this.ctx2.rect.startX = this.mouseY;
this.ctx2.rect.startY = this.mouseX;
this.dragBR = true;
}
if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY)) {
this.dragTL = true;
}
else if (this.checkCloseEnough(this.mouseX, this.ctx2.rect.startX + this.ctx2.rect.w/2) && this.checkCloseEnough(this.mouseY, this.ctx2.rect.startY + this.ctx2.rect.h)) {
this.dragBR = true;
}
else {
// handle not resizing
}

Related

Not able to get ng-bind-html to work

Problem: I am trying to use ng-bind-html but I am getting the following errors on the console:
The following is the controller where I am calling ngSanitize:
and using the following file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
In my form, I do the following to use ng-bind-html. So when I try to see my results, it is still rendering the &rather then &:
<div ng-bind-html="e.Specialty"></div>
and the following is what occurs in the Specialty:
Any help would be appreciated.
#lealceldeiro: Here is the controller in which I am trying to implement your suggestion but not sure where I will add it:
(
function(){
var $scope, $location;
var indexApp = angular.module('indexApp',['ui.bootstrap', 'ngSanitize']);
indexApp.controller('IndexController',function($scope,$sce,$http,$location,anchorSmoothScroll){
$scope.Lang = 'initVal';
$scope.ShowResults = false;
$scope.ShowDesc = true;
$scope.NoResults = false;
$scope.currentPage = 1;
$scope.maxPageNumbersToShow = 10;
$scope.formModel = {};
$scope.searchMode = 0;
$scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }];
$scope.Specialties = [{'value':'Family practice'},{'value':'General practice'},{'value':'Internal medicine'},{'value':'Pediatrics'}];
$scope.Gender = [{'value':'Male'},{'value':'Female'}];
$scope.Languages = {};
$scope.Cities = {};
//$scope.lastAction = '';
$scope.searchParam = {};
$("input").removeAttr('disabled');
$scope.searchParam.Distance = $scope.miles[0];
$scope.GetCurrentZip = function (){
try{
var lon, lat;
// console.log('starting geoposition code.');
if("geolocation" in navigator){
window.navigator.geolocation.getCurrentPosition(function(pos){
lat = pos.coords.latitude.toFixed(3);
lon = pos.coords.longitude.toFixed(3);
// console.log(lat + ' ' + lon);
$http.get("/Brokers-en-us/includes/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon)
.then(function(response){
$scope.searchParam.Zip = response.data;
})
})
}
else{ console.log('No geolocation'); }
}
catch(err) { console.log(err.message); }
}
$scope.GetCityList = function (){
try{
$http.get("/Brokers-en-us/includes/remote/ReturnCityList.cfm")
.then(function(response){
$scope.Cities = response.data.Cities;
})
}
catch(err){}
}
$scope.GetLangList = function (){
try{
$http.get("/Brokers-en-us/includes/remote/ReturnLangList.cfm")
.then(function(response){
$scope.Languages = response.data.Languages;
})
}
catch(err){}
}
$scope.SearchProvider = function(searchParam){
try{
//debugger;
$scope.searchMode = 1;
var queryString='';
if($scope.formModel && $scope.formModel !== searchParam){
$scope.resultsCount = 0;
currentPage = 1;
}
if(searchParam){
//debugger;
$scope.formModel = searchParam;
for(var param in searchParam){
if(searchParam.hasOwnProperty(param)){
var paramValue = searchParam[param].value ? searchParam[param].value : searchParam[param];
if (paramValue.length > 0)
queryString += param + '=' + paramValue + '&';
}
}
}
console.log(queryString);
queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;
$http.get("/Brokers-en-us/includes/remote/ReturnProvidersList.cfm" + queryString)
.then(function(response){
$scope.providers = response.data.provider;
$scope.resultsCount = response.data.rowCount;
if (!$scope.providers){
$scope.NoResults = true;
$scope.ShowResults = false;
$scope.ShowDesc = false;
}
else{
$scope.NoResults = false;
$scope.ShowResults = true;
$scope.ShowDesc = false;
}
})
}
catch(err){ alert('No response.: ' + err.message); }
}
/*Testing purposes*/
$scope.clearTopForm = function(searchParam){
//console.log("I clicked this.")
}
/*Clears the drop downs and input fields*/
$scope.$watch('searchParam.Distance', function(newValue, oldValue) {
//debugger;
if(newValue != ''){
//$scope.lastAction = 'miles';
$scope.searchParam.City = '';
$scope.searchParam.Specialty = '';
$scope.searchParam.Gender = '';
}
});
$scope.$watch('searchParam.Zip', function(newValue, oldValue) {
if(newValue != ''){
//$scope.lastAction = 'miles';
$scope.searchParam.Gender = '';
$scope.searchParam.Specialty = '';
$scope.searchParam.City = '';
}
});
$scope.cityChange = function(){
//debugger;
if($scope.searchParam.City != ''){
//$scope.lastAction = 'city';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.specialtyChange = function(){
//debugger;
if($scope.searchParam.Specialty != ''){
//$scope.lastAction = 'specialty';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.genderChange = function(){
//debugger;
if($scope.searchParam.Gender != ''){
//$scope.lastAction = 'gender';
$scope.searchParam.Distance = '';
$scope.searchParam.Zip = '';
}
}
$scope.$watchGroup(['currentPage'], function(){
try{
if($scope.searchMode == 1){
$scope.SearchProvider($scope.formModel);
}
}
catch(err){}
});
$scope.GetCityList();
$scope.GetLangList();
$scope.GetCurrentZip();
$scope.gotoElement = function (eID){
//http://jsfiddle.net/brettdewoody/y65G5/
// set the location.hash to the id of
// the element you wish to scroll to.
//$location.hash('bottom');
// call $anchorScroll()
var browserWidth = screen.availWidth;
if (browserWidth < 768)
anchorSmoothScroll.scrollTo(eID);
};
});
indexApp.service('anchorSmoothScroll', function(){
this.scrollTo = function(eID) {
// This scrolling function
// is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
};
});
indexApp.directive('allowPattern',[allowPatternDirective]);
indexApp.directive('popPopup',[describePopup]);
indexApp.directive('pop', function pop ($tooltip, $timeout) {
var tooltip = $tooltip('pop', 'pop', 'event');
var compile = angular.copy(tooltip.compile);
tooltip.compile = function (element, attrs) {
var first = true;
attrs.$observe('popShow', function (val) {
if (JSON.parse(!first || val || false)) {
$timeout(function(){
element.triggerHandler('event');
});
}
first = false;
});
return compile(element, attrs);
};
return tooltip;
});
indexApp.filter('PhoneNumber', function(){
return function(phoneNumber){
var dash = '-';
var openParen = '(';
var closeParen = ') ';
if(phoneNumber){
var pn = phoneNumber;
pn = [pn.slice(0, 6), dash, pn.slice(6)].join('');
pn = openParen + [pn.slice(0, 3), closeParen, pn.slice(3)].join('');
return pn;
}
return phoneNumber;
}
});
indexApp.filter('Zip', function(){
return function(zipcode){
var dash = '-';
if(zipcode && zipcode.length > 5){
var zc = zipcode;
zc = [zc.slice(0, 5), dash, zc.slice(5)].join('');
return zc;
}
return zipcode;
}
});
function allowPatternDirective(){
return{
restrict: "A",
compile: function(tElement, tAttrs){
return function(scope, element, attrs){
element.bind("keypress", function(event){
var keyCode = event.which || event.keyCode;
var keyCodeChar = String.fromCharCode(keyCode);
if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){
event.preventDefault();
return false;
}
});
}
}
}
}
function describePopup(){
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover.html'
};
}
})();
(function($) {
// #todo Document this.
$.extend($,{ placeholder: {
browser_supported: function() {
return this._supported !== undefined ?
this._supported :
( this._supported = !!('placeholder' in $('<input type="text">')[0]) );
},
shim: function(opts) {
var config = {
color: '#888',
cls: 'placeholder',
selector: 'input[placeholder], textarea[placeholder]'
};
$.extend(config,opts);
return !this.browser_supported() && $(config.selector)._placeholder_shim(config);
}
}});
$.extend($.fn,{
_placeholder_shim: function(config) {
function calcPositionCss(target)
{
var op = $(target).offsetParent().offset();
var ot = $(target).offset();
return {
top: ot.top - op.top,
left: ot.left - op.left,
width: $(target).width()
};
}
function adjustToResizing(label) {
var $target = label.data('target');
if(typeof $target !== "undefined") {
label.css(calcPositionCss($target));
$(window).one("resize", function () { adjustToResizing(label); });
}
}
return this.each(function() {
var $this = $(this);
if( $this.is(':visible') ) {
if( $this.data('placeholder') ) {
var $ol = $this.data('placeholder');
$ol.css(calcPositionCss($this));
return true;
}
var possible_line_height = {};
if( !$this.is('textarea') && $this.css('height') != 'auto') {
possible_line_height = { lineHeight: $this.css('height'), whiteSpace: 'nowrap' };
}
var isBorderBox = ($this.css('box-sizing') === 'border-box');
var isTextarea = $this.is('textarea');
var ol = $('<label />')
.text($this.attr('placeholder'))
.addClass(config.cls)
.css($.extend({
position:'absolute',
display: 'inline',
'float':'none',
overflow:'hidden',
textAlign: 'left',
color: config.color,
cursor: 'text',
paddingTop: !isTextarea && isBorderBox ? '0' : $this.css('padding-top'),
paddingRight: $this.css('padding-right'),
paddingBottom: !isTextarea && isBorderBox ? '0' : $this.css('padding-bottom'),
paddingLeft: $this.css('padding-left'),
fontSize: $this.css('font-size'),
fontFamily: $this.css('font-family'),
fontStyle: $this.css('font-style'),
fontWeight: $this.css('font-weight'),
textTransform: $this.css('text-transform'),
backgroundColor: 'transparent',
zIndex: 99,
}, possible_line_height))
.css(calcPositionCss(this))
.attr('for', this.id)
.data('target',$this)
.click(function(){
if (!$(this).data('target').is(':disabled')) {
$(this).data('target').focus();
}
})
.insertBefore(this);
$this
.data('placeholder', ol)
.on('keydown', function () {
ol.hide();
})
.on('blur change', function () {
ol[$this.val().length ? 'hide' : 'show']();
})
.triggerHandler('blur');
$(window).one("resize", function () { adjustToResizing(ol); });
}
});
}
});
})(jQuery);
jQuery(document).add(window).bind('ready load', function() {
if (jQuery.placeholder) {
jQuery.placeholder.shim();
}
});
When you use ng-bind-html, AngularJS sometimes consider some contents as unsafe (as your case), so you need to use the $sce service in order to "mark" this content as safe (to be used) like this:
$sce.trustAsHtml("CLINICAL & SOCIAL"); (See demo below)
From $sanitize
The input is sanitized by parsing the HTML into tokens. All safe
tokens (from a whitelist) are then serialized back to properly escaped
html string. This means that no unsafe input can make it into the
returned string.
In this case the "unsafe" part is &
angular
.module('app', [])
.controller('ctrl', ctrl);
function ctrl($scope, $sce) {
$scope.Specialty = $sce.trustAsHtml("CLINICAL & SOCIAL");
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
<div ng-app="app" ng-controller="ctrl">
Specialty: <span ng-bind-html="Specialty"></span>
</div>

Making invisible sprite with phaser

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.

Quintus Game Development

I am trying to pause between levels in this game but the pause feature wont work. Any help would be great. Currently the code just keeps getting stuck in a loop and prints out Next Level.
The level system is supposed to work when this.p.levelData.nextLevel is true but it keeps looping.
Any help would be great.
Quintus.ZombiesGameplay = function(Q) {
//game level
Q.Sprite.extend('Level', {
init: function(p) {
this._super(p, {
asset: '/assets/images/background.png',
type: Q.SPRITE_GROUND,
x: 90 + 1024/2,
y: 768/2,
w: 1024,
h: 768,
sunFrequency: {min: 3,max: 10}, //min and max number of seconds for sun to appear
});
this.timeNextSun = this.getTimeNextSun(); //time for the next sun to appear
//level data
this.zombieIndex = 0; //current index from zombies array
this.numZombies = this.p.levelData.zombies.length;
this.levelTime = 0; //keep track of the level duration
//save the position of each plant in a grid
this.plantsGrid = new Array(new Array(7), new Array(7), new Array(7), new Array(7), new Array(7), new Array(7));
this.on('touch');
Q.audio.play('/assets/audio/ZombiesOnYourLawn.mp3');
},
step: function(dt) {
//update level duration
this.levelTime += dt;
//check for level passed
if(this.p.levelData.duration < this.levelTime) {
if(this.p.levelData.nextLevel) {
// Q.stageScene("level", {levelData: Q.assets[this.p.levelData.nextLevel]});
// Q.stage().pause();
// Q.stage().unpause();
// debugger;
nextLevel();
// pauseGame();
// unPauseGame();
}else {
endGame();
// Q.stageScene('level', {levelData: Q.assets['/assets/data/level1.json']});
// Q.stage().pause();
// Q.stage().unpause();
}
}
//create zombies at the defined times
if(this.zombieIndex < this.numZombies) {
var currentZombie = this.p.levelData.zombies[this.zombieIndex];
if(this.levelTime >= currentZombie.time) {
var zombieData = Q.zombieTypes[currentZombie.type];
var newZombie = new Q.Zombie(
Q._extend(zombieData, {y: currentZombie.row * 120 + 60})
);
this.stage.insert(newZombie);
this.zombieIndex++;
}
}
//update sun generation timing
this.timeNextSun -= dt;
if(this.timeNextSun <= 0) {
this.timeNextSun = this.getTimeNextSun();
//create sun in the sun stage
Q.stage(1).insert(new Q.Sun());
}
},
touch: function(touch) {
//if a plant is selected
if(Q.state.get('currentPlant')) {
//get plantsGrid coordinates
var row = Math.floor((touch.y)/120);
var col = Math.floor((touch.x - 240)/120);
if(row >= 0 && row < this.plantsGrid.length && col >= 0 && col < this.plantsGrid[0].length) {
if(!this.plantsGrid[row][col] && Q.state.get('sun') >= Q.state.get('currentPlant').cost) {
Q.state.dec('sun', Q.state.get('currentPlant').cost);
var newPlant = new Q.Plant(Q._extend({x: 240 + 60 + col*120, y: 60 + row*120}, Q.state.get('currentPlant')));
this.stage.insert(newPlant);
this.plantsGrid[row][col] = newPlant;
newPlant.p.gridRow = row;
newPlant.p.gridCol = col;
}
}
}
},
getTimeNextSun: function() {
return this.p.sunFrequency.min + Math.random()*(this.p.sunFrequency.max - this.p.sunFrequency.min);
},
});
}
function nextLevel(){
console.log('NEXT LEVEL');
Q.stageScene("nextLevel",1, { label: "LEVEL COMPLETED!" });
Q.scene('nextLevel',function(stage) {
var container = stage.insert(new Q.UI.Container({
x: Q.width/2, y: Q.height/2, fill: "rgba(0,0,0,0.5)"
}));
var nextLevelButton = container.insert(new Q.UI.Button({ x: 0, y: 0, fill: "#CCCCCC",
label: "Next Level" }))
var label = container.insert(new Q.UI.Text({x:10, y: -10 - nextLevelButton.p.h, fill: "#FFFFFF",
label: stage.options.label }));
nextLevelButton.on("click",function() {
alert("test");
Q.stageScene("level", {levelData: Q.assets[this.p.levelData.nextLevel] });
});
container.fit(20);
});
pauseGame();
};
function endGame(){
console.log('YOU WON!');
Q.stageScene("endGame",1, { label: "You Have Won The Game!" });
Q.scene('endGame',function(stage) {
var container = stage.insert(new Q.UI.Container({
x: Q.width/2, y: Q.height/2, fill: "rgba(0,0,0,0.5)"
}));
var button = container.insert(new Q.UI.Button({ x: 0, y: 0, fill: "#CCCCCC",
label: "Play Again" }))
var label = container.insert(new Q.UI.Text({x:10, y: -10 - button.p.h, fill: "#FFFFFF",
label: stage.options.label }));
button.on("click",function() {
Q.clearStages();
Q.stageScene('level', {levelData: Q.assets['/assets/data/level1.json']});
});
container.fit(20);
});
// pauseGame();
};
function pauseGame(){
console.log("Game Paused");
Q.stage().pause()
};
function unPauseGame(){
Q.stage().unpause()
};

how to show two d3.js diagrams on the same page

i read lots of threads and the Mike's blog but i haven't found how to solve my problem.
I'm using the donut chart of D3.js and everything works fine.
I use that code and change the value for each diagram:
var w = 650;
var h = 400;
var r = 150;
var ir = 75;
var textOffset = 24;
var tweenDuration = 1050;
//OBJECTS TO BE POPULATED WITH DATA LATER
var lines, valueLabels, nameLabels;
var pieData = [];
var oldPieData = [];
var filteredPieData = [];
//D3 helper function to populate pie slice parameters from array data
var donut = d3.layout.pie().value(function(d){
return d.itemValue;
});
//D3 helper function to create colors from an ordinal scale
var color = d3.scale.category20c();
//D3 helper function to draw arcs, populates parameter "d" in path object
var arc = d3.svg.arc()
.startAngle(function(d){ return d.startAngle; })
.endAngle(function(d){ return d.endAngle; })
.innerRadius(ir)
.outerRadius(r);
///////////////////////////////////////////////////////////
// GENERATE FAKE DATA /////////////////////////////////////
///////////////////////////////////////////////////////////
var data;
var dataStructure = [
{
"data":[
{
"itemLabel":"Social Media",
"itemValue":90
},
{
"itemLabel":"Blogs",
"itemValue":30
},
{
"itemLabel":"Text Messaging",
"itemValue":60
},
{
"itemLabel":"Email",
"itemValue":90
},
],
"label":"2007"
},
{
"data":[
{
"itemLabel":"Social Media",
"itemValue":80
},
{
"itemLabel":"Blogs",
"itemValue":20
},
{
"itemLabel":"Text Messaging",
"itemValue":70
},
{
"itemLabel":"Email",
"itemValue":90
},
],
"label":"2009"
},
{
"data":[
{
"itemLabel":"Social Media",
"itemValue":70
},
{
"itemLabel":"Blogs",
"itemValue":20
},
{
"itemLabel":"Text Messaging",
"itemValue":70
},
{
"itemLabel":"Email",
"itemValue":90
},
],
"label":"2011"
},
{
"data":[
{
"itemLabel":"Social Media",
"itemValue":60
},
{
"itemLabel":"Blogs",
"itemValue":20
},
{
"itemLabel":"Text Messaging",
"itemValue":70
},
{
"itemLabel":"Email",
"itemValue":90
},
],
"label":"2013"
},
];
///////////////////////////////////////////////////////////
// CREATE VIS & GROUPS ////////////////////////////////////
///////////////////////////////////////////////////////////
var vis = d3.select("#pie-chart").append("svg:svg")
.attr("width", w)
.attr("height", h);
//GROUP FOR ARCS/PATHS
var arc_group = vis.append("svg:g")
.attr("class", "arc")
.attr("transform", "translate(" + (w/2) + "," + (h/2) + ")");
//GROUP FOR LABELS
var label_group = vis.append("svg:g")
.attr("class", "label_group")
.attr("transform", "translate(" + (w/2) + "," + (h/2) + ")");
//GROUP FOR CENTER TEXT
var center_group = vis.append("svg:g")
.attr("class", "center_group")
.attr("transform", "translate(" + (w/2) + "," + (h/2) + ")");
//PLACEHOLDER GRAY CIRCLE
// var paths = arc_group.append("svg:circle")
// .attr("fill", "#EFEFEF")
// .attr("r", r);
///////////////////////////////////////////////////////////
// CENTER TEXT ////////////////////////////////////////////
///////////////////////////////////////////////////////////
//WHITE CIRCLE BEHIND LABELS
var whiteCircle = center_group.append("svg:circle")
.attr("fill", "white")
.attr("r", ir);
///////////////////////////////////////////////////////////
// STREAKER CONNECTION ////////////////////////////////////
///////////////////////////////////////////////////////////
// to run each time data is generated
function update(number) {
data = dataStructure[number].data;
oldPieData = filteredPieData;
pieData = donut(data);
var sliceProportion = 0; //size of this slice
filteredPieData = pieData.filter(filterData);
function filterData(element, index, array) {
element.name = data[index].itemLabel;
element.value = data[index].itemValue;
sliceProportion += element.value;
return (element.value > 0);
}
//DRAW ARC PATHS
paths = arc_group.selectAll("path").data(filteredPieData);
paths.enter().append("svg:path")
.attr("stroke", "white")
.attr("stroke-width", 0.5)
.attr("fill", function(d, i) { return color(i); })
.transition()
.duration(tweenDuration)
.attrTween("d", pieTween);
paths
.transition()
.duration(tweenDuration)
.attrTween("d", pieTween);
paths.exit()
.transition()
.duration(tweenDuration)
.attrTween("d", removePieTween)
.remove();
//DRAW TICK MARK LINES FOR LABELS
lines = label_group.selectAll("line").data(filteredPieData);
lines.enter().append("svg:line")
.attr("x1", 0)
.attr("x2", 0)
.attr("y1", -r-3)
.attr("y2", -r-15)
.attr("stroke", "gray")
.attr("transform", function(d) {
return "rotate(" + (d.startAngle+d.endAngle)/2 * (180/Math.PI) + ")";
});
lines.transition()
.duration(tweenDuration)
.attr("transform", function(d) {
return "rotate(" + (d.startAngle+d.endAngle)/2 * (180/Math.PI) + ")";
});
lines.exit().remove();
//DRAW LABELS WITH PERCENTAGE VALUES
valueLabels = label_group.selectAll("text.value").data(filteredPieData)
.attr("dy", function(d){
if ((d.startAngle+d.endAngle)/2 > Math.PI/2 && (d.startAngle+d.endAngle)/2 < Math.PI*1.5 ) {
return 5;
} else {
return -7;
}
})
.attr("text-anchor", function(d){
if ( (d.startAngle+d.endAngle)/2 < Math.PI ){
return "beginning";
} else {
return "end";
}
})
.text(function(d){
var percentage = (d.value/sliceProportion)*100;
return percentage.toFixed(1) + "%";
});
valueLabels.enter().append("svg:text")
.attr("class", "value")
.attr("transform", function(d) {
return "translate(" + Math.cos(((d.startAngle+d.endAngle - Math.PI)/2)) * (r+textOffset) + "," + Math.sin((d.startAngle+d.endAngle - Math.PI)/2) * (r+textOffset) + ")";
})
.attr("dy", function(d){
if ((d.startAngle+d.endAngle)/2 > Math.PI/2 && (d.startAngle+d.endAngle)/2 < Math.PI*1.5 ) {
return 5;
} else {
return -7;
}
})
.attr("text-anchor", function(d){
if ( (d.startAngle+d.endAngle)/2 < Math.PI ){
return "beginning";
} else {
return "end";
}
}).text(function(d){
var percentage = (d.value/sliceProportion)*100;
return percentage.toFixed(1) + "%";
});
valueLabels.transition().duration(tweenDuration).attrTween("transform", textTween);
valueLabels.exit().remove();
//DRAW LABELS WITH ENTITY NAMES
nameLabels = label_group.selectAll("text.units").data(filteredPieData)
.attr("dy", function(d){
if ((d.startAngle+d.endAngle)/2 > Math.PI/2 && (d.startAngle+d.endAngle)/2 < Math.PI*1.5 ) {
return 17;
} else {
return 5;
}
})
.attr("text-anchor", function(d){
if ((d.startAngle+d.endAngle)/2 < Math.PI ) {
return "beginning";
} else {
return "end";
}
}).text(function(d){
return d.name;
});
nameLabels.enter().append("svg:text")
.attr("class", "units")
.attr("transform", function(d) {
return "translate(" + Math.cos(((d.startAngle+d.endAngle - Math.PI)/2)) * (r+textOffset) + "," + Math.sin((d.startAngle+d.endAngle - Math.PI)/2) * (r+textOffset) + ")";
})
.attr("dy", function(d){
if ((d.startAngle+d.endAngle)/2 > Math.PI/2 && (d.startAngle+d.endAngle)/2 < Math.PI*1.5 ) {
return 17;
} else {
return 5;
}
})
.attr("text-anchor", function(d){
if ((d.startAngle+d.endAngle)/2 < Math.PI ) {
return "beginning";
} else {
return "end";
}
}).text(function(d){
return d.name;
});
nameLabels.transition().duration(tweenDuration).attrTween("transform", textTween);
nameLabels.exit().remove();
}
///////////////////////////////////////////////////////////
// FUNCTIONS //////////////////////////////////////////////
///////////////////////////////////////////////////////////
// Interpolate the arcs in data space.
function pieTween(d, i) {
var s0;
var e0;
if(oldPieData[i]){
s0 = oldPieData[i].startAngle;
e0 = oldPieData[i].endAngle;
} else if (!(oldPieData[i]) && oldPieData[i-1]) {
s0 = oldPieData[i-1].endAngle;
e0 = oldPieData[i-1].endAngle;
} else if(!(oldPieData[i-1]) && oldPieData.length > 0){
s0 = oldPieData[oldPieData.length-1].endAngle;
e0 = oldPieData[oldPieData.length-1].endAngle;
} else {
s0 = 0;
e0 = 0;
}
var i = d3.interpolate({startAngle: s0, endAngle: e0}, {startAngle: d.startAngle, endAngle: d.endAngle});
return function(t) {
var b = i(t);
return arc(b);
};
}
function removePieTween(d, i) {
s0 = 2 * Math.PI;
e0 = 2 * Math.PI;
var i = d3.interpolate({startAngle: d.startAngle, endAngle: d.endAngle}, {startAngle: s0, endAngle: e0});
return function(t) {
var b = i(t);
return arc(b);
};
}
function textTween(d, i) {
var a;
if(oldPieData[i]){
a = (oldPieData[i].startAngle + oldPieData[i].endAngle - Math.PI)/2;
} else if (!(oldPieData[i]) && oldPieData[i-1]) {
a = (oldPieData[i-1].startAngle + oldPieData[i-1].endAngle - Math.PI)/2;
} else if(!(oldPieData[i-1]) && oldPieData.length > 0) {
a = (oldPieData[oldPieData.length-1].startAngle + oldPieData[oldPieData.length-1].endAngle - Math.PI)/2;
} else {
a = 0;
}
var b = (d.startAngle + d.endAngle - Math.PI)/2;
var fn = d3.interpolateNumber(a, b);
return function(t) {
var val = fn(t);
return "translate(" + Math.cos(val) * (r+textOffset) + "," + Math.sin(val) * (r+textOffset) + ")";
};
}
$( "#slider" ).slider({
value: 0,
min: 0,
max: 3,
step: 1,
slide: function( event, ui ) {
update(ui.value);
console.log(ui.value);
}
})
.each(function() {
//
// Add labels to slider whose values
// are specified by min, max and whose
// step is set to 1
//
// Get the options for this slider
var opt = $(this).data().uiSlider.options;
// Get the number of possible values
var vals = opt.max - opt.min;
// Space out values
for (var i = 0; i <= vals; i++) {
var el = $('<label>'+dataStructure[i].label+'</label>').css('left',(i/vals*100)+'%');
$( "#slider" ).append(el);
}
});
update(0);
Here is the Jsfiddle of the diagram i'm using:
jsfiddle.net/brusasu/AqP73/
I created two html page, each for the diagrams with the value i need to show.
My question is how to edit the code in a way where i can use the two diagrams in the same html page.
Thanks in advance
Oki Doki. I'm no expert in these things, but looking at the css in your jsfiddle, it appears to be missing the styles that you might want for the divs "slidercontainer2", "pie-chart2 and "slider2".
Make sure that you have these properly duplicated and that will at least get you closer.

FabricJS - How to dragging an object in Shape filled object?

Im trying to drawing line Shape (fabric.Line).
and then after drawn shape. it filled image.
When finished drawing an shape, I want to drag an filled image (inside Shape)
Here is the jsfiddle >> http://jsfiddle.net/dTpVw/
var canvas = new fabric.Canvas('c', { selection:false });
var mode = "add";
var currentShape;
canvas.observe("mouse:move", function (event) {
var pos = canvas.getPointer(event.e);
if (mode === "edit" && currentShape) {
if (currentShape.type === "line") {
currentShape.set({
x2 : pos.x,
y2 : pos.y
});
canvas.renderAll();
} else if (currentShape.type === "polygon") {
var points = currentShape.get("points");
points[points.length - 1].x = pos.x - currentShape.get("left");
points[points.length - 1].y = pos.y - currentShape.get("top");
currentShape.set({
points : points
});
canvas.renderAll();
}
}
});
canvas.observe("mouse:down", function (event) {
var pos = canvas.getPointer(event.e);
if (mode === "add") {
var polygon = new fabric.Line([ pos.x, pos.y, pos.x + 2,
pos.y + 2 ], {
fill : 'red'
});
currentShape = polygon;
canvas.add(currentShape);
mode = "edit";
} else if (mode === "edit" && currentShape
&& currentShape.type === "line") {
// replace line with polygon
canvas.remove(currentShape);
var points = [];
points.push({
x : currentShape.x1 - pos.x,
y : currentShape.y1 - pos.y
});
points.push({
x : currentShape.x2 - pos.x,
y : currentShape.y2 - pos.y
});
points.push({
x : currentShape.x2 - pos.x + 5,
y : currentShape.y2 - pos.y + 5
});
var polygon = new fabric.Polygon(points, {
fill : 'blue',
left : pos.x,
top : pos.y,
opacity: 0.5 // 투명도 적용
});
canvas.add(polygon);
Spolygon = polygon;
currentShape = polygon;
canvas.renderAll();
} else if (mode === "edit" && currentShape
&& currentShape.type === "polygon") {
var points = currentShape.get("points");
points.push({
x : pos.x - currentShape.get("left"),
y : pos.y - currentShape.get("top")
});
currentShape.set({
points : points
});
canvas.renderAll();
}
});
function loadPattern(url) {
fabric.util.loadImage(url, function(img) {
console.log(Spolygon);
Spolygon.fill = new fabric.Pattern({
source : img,
repeat : 'repeat'
});
canvas.renderAll();
});
Spolygon.hasControls = false;
// Spolygon.selectable = false;
Spolygon.hasRotatingPoint = false;
Spolygon.lockMovementX = true;
Spolygon.lockMovementY = true;
}
function dblClickHandler(event)
{
currentShape.setCoords();
mode ="add2";
loadPattern('http://fabricjs.com/assets/retina_wood.png');
};
fabric.util.addListener(fabric.document, 'dblclick', dblClickHandler);
//fabric.util.removeListener(canvas.upperCanvasEl, 'dblclick', dblClickHandler);
Thank you for reading my question... Please someone help me T_T
Try something like this in your dblClickHandler event:
function dblClickHandler(event)
{
currentShape.setCoords();
mode ="add2";
loadPattern('http://fabricjs.com/assets/retina_wood.png');
//alert(currentShape.height);
//alert(currentShape.width);
currentShape.hasControls = true;
currentShape.hasRotatingPoint = true;
currentShape.lockMovementX = false;
currentShape.lockMovementY = false;
canvas.setActiveObject(currentShape);
canvas.renderAll();
};
I have updated your fiddle: http://jsfiddle.net/dTpVw/3/
I hope it helps...