Update dimple.js chart when select a new option - dimple.js

<select id="cs" name="cs" >
<option value = "HIV+TB" >HIV+TB</option>
<option value = "TB">TB</option>
</select>
<button id="btn">Click Me</button>
<div id="chartContainer">
<script type="text/javascript">
var dropdown = d3.select("#cs")
var cs2 = dropdown.node().options[dropdown.node().selectedIndex].value;
d3.csv("test.csv", function (data) {
var svg = dimple.newSvg("#chartContainer", 590, 600);
var myChart = new dimple.chart(svg, data1990);
myChart.setBounds(105, 25, 475, 465)
myChart.showGridlines = true;
myChart.addCategoryAxis("x", ["measure","sex","year"]);
myChart.addCategoryAxis("y", "age_name");
var z = myChart.addMeasureAxis("z", "rt_mean");
var s = myChart.addSeries("sex", dimple.plot.bubble);
s.aggregate = dimple.aggregateMethod.max;
myChart.addLegend(240, 10, 330, 20, "right");
myChart.draw();
d3.select("#btn").on("click", function() {
myChart.data = data.filter(function(d) { return d.cause_short == cs2; });
myChart.draw(1000);
});
});
</script>
The problem is the code want to add a new chart in addition to the exist one.
How can I update the chart after clicking the new option.

Here's an example to redraw the chart with random numbers whenever the button is clicked. Hopefully this will give you enough to work your example:
var svg = dimple.newSvg("#chartContainer", 590, 400);
var data = [
{ Animal: "Cats", Value: (Math.random() * 1000000) },
{ Animal: "Dogs", Value: (Math.random() * 1000000) },
{ Animal: "Mice", Value: (Math.random() * 1000000) }
];
var myChart = new dimple.chart(svg, data);
myChart.setBounds(60, 30, 510, 305)
var x = myChart.addCategoryAxis("x", "Animal");
x.addOrderRule(["Cats", "Dogs", "Mice"]);
myChart.addMeasureAxis("y", "Value");
myChart.addSeries(null, dimple.plot.bar);
myChart.draw();
d3.select("#btn").on("click", function() {
myChart.data = [
{ Animal: "Cats", Value: (Math.random() * 1000000) },
{ Animal: "Dogs", Value: (Math.random() * 1000000) },
{ Animal: "Mice", Value: (Math.random() * 1000000) }
];
myChart.draw(1000);
});
And a working example here:
http://jsfiddle.net/nf57j/

Related

d3.js | projection.rotate() return value [NaN, 0, 0]

I want to rotate the globe canvas using projection.rotate() but it return value [NaN, 0, 0].
<template lang="html">
<div class="map" style="width:100vw;height:100vh">
<canvas id="globe"></canvas>
</div>
</template>
<script lang="js">
import * as d3 from "d3";
import * as topojson from "topojson-client";
export default {
name: 'vue',
data() {
return {
angles: { x: -20, y: 40, z: 0 },
canvas: null,
context: null,
countries:null,
countryList:null,
autorotate:null,
lastTime : d3.now(),
now:null,
diff:null,
roation:null,
scaleFactor: 0.6,
degPerSec : 6,
degPerMs: this.degPerSec / 1000,
width:null,
height:null,
water : {type: 'Sphere'},
colorWater : '#0099cf',
colorLand : '#77fc2f',
colorGraticule : '#0099cf',
colorCountry : '#77fc2f',
land:null,
currentCountry:null,
graticule: d3.geoGraticule10(),
projection: d3.geoOrthographic().precision(0.1),
path : null,
}
},
mounted() {
this.canvas = document.getElementById('globe');
this.context = this.canvas.getContext('2d');
this.path = d3.geoPath(this.projection).context(this.context);
this.loadData((world, cList)=> {
this.land = topojson.feature(world, world.objects.land);
this.countries = topojson.feature(world, world.objects.countries);
this.countryList = cList;
window.addEventListener('resize', this.scale);
this.scale();
this.autorotate = d3.timer(this.rotate);
});
},
methods: {
loadData(cb) {
d3.json('https://unpkg.com/world-atlas#1/world/110m.json').then(function(world) {
d3.tsv('https://gist.githubusercontent.com/mbostock/4090846/raw/07e73f3c2d21558489604a0bc434b3a5cf41a867/world-country-names.tsv').then( function(countries) {
cb(world, countries)
})
})
},
rotate(elapsed) {
this.now = d3.now();
this.diff = this.now - this.lastTime;
if (elapsed < 300) { //this.diff !== elapsed
let rotation = this.projection.rotate();
console.log(rotation);
rotation[0] += this.diff * this.degPerMs;
this.projection.rotate(rotation);
this.render();
}
this.lastTime = this.now;
},
render() {
this.context.clearRect(0, 0, this.width, this.height);
this.fill(this.water, this.colorWater)
this.stroke(this.graticule, this.colorGraticule)
this.fill(this.land, this.colorLand)
if (this.currentCountry) {
this.fill(this.currentCountry, this.colorCountry)
}
},
fill(obj, color) {
this.context.beginPath()
this.path(obj)
this.context.fillStyle = color
this.context.fill()
},
stroke(obj, color) {
this.context.beginPath()
this.path(obj)
this.context.strokeStyle = color
this.context.stroke()
},
scale() {
this.width = document.querySelector(".map").clientWidth;
this.height = document.querySelector(".map").clientHeight;
this.canvas.setAttribute('width', this.width);
this.canvas.setAttribute('height', this.height);
this.projection
.scale((this.scaleFactor * Math.min(this.width, this.height)) / 2)
.translate([this.width / 2, this.height / 2])
this.render();
}
},
}
</script>
you can check my issue here: https://codesandbox.io/s/globe-issus-q2s1s
example rotate demo: https://codepen.io/Share2U/pen/dyWQoGv
Thank you for your help.
The issue lies in the following line:
degPerMs: this.degPerSec / 1000,
this.degPerSec is not available because you can't access other data properties inside data. Therefore rotation[0] += this.diff * this.degPerMs; is returning NaN.
To fix this you can set a variable before exporting the module.
E.g.:
<script lang="js">
import * as d3 from "d3";
import * as topojson from "topojson-client";
const DEG_PER_SEC = 6;
export default {
name: 'vue',
data() {
return {
...
degPerMs: DEG_PER_SEC / 1000,
...
}
}
}
</script>

Instagram API / Flickity Carousel

Trying to integrate this on a site: https://github.com/mangcoding/instagram-feeder
I don't know enough about APIs to get it working for a username instead of a tag. I'm thinking it might have something to do with this line: let instaData = data.edge_hashtag_to_media.edges;
Anyone know how I could accomplish, thanks!
<script charset="utf-8">
(function ($) {
$(window).on('load', function () {
var limit = 20;
$.instagramFeed({
'tag': 'data', // want this to be 'username': 'data',
'get_data': true,
'callback': function (data) {
let instaData = data.edge_hashtag_to_media.edges;
instaData.slice(0, limit).filter(x => x.node.edge_media_to_caption.edges.length > 0)
.forEach(item => {
let node = item.node;
let source = $("#instagram-template").html();
let template = Handlebars.compile(source);
let taken = new Date(node.taken_at_timestamp * 1000)
.toDateString().substr(4);
//change format to month date,year
let created = taken.slice(0, 6) + ',' + taken.slice(6);
let context = {
link: "https://www.instagram.com/p/" + node
.shortcode + "/",
image_url: node.display_url,
countLikes: node.edge_liked_by.count,
caption: node.edge_media_to_caption.edges[0].node
.text,
created: created
};
let html = template(context);
$("#instagramFeed").append(html);
});
$('#instagramFeed').flickity({
cellAlign: 'left',
wrapAround: true,
pageDots: false,
setGallerySize: false,
prevNextButtons: true,
arrowShape: { "x0": 20, "x1": 60, "y1": 40, "x2": 60, "y2": 35, "x3": 25 }
});
}
});
});
})(jQuery);
</script>
Figured it out:
let instaData = data.edge_owner_to_timeline_media.edges;
vs
let instaData = data.edge_hashtag_to_media.edges;
<script charset="utf-8">
(function ($) {
$(window).on('load', function () {
var limit = 20;
$.instagramFeed({
'username': 'myusername',
'get_data': true,
'callback': function (data) {
let instaData = data.edge_owner_to_timeline_media.edges;
instaData.slice(0, limit).filter(x => x.node.edge_media_to_caption.edges.length > 0)
.forEach(item => {
let node = item.node;
let source = $("#instagram-template").html();
let template = Handlebars.compile(source);
let taken = new Date(node.taken_at_timestamp * 1000)
.toDateString().substr(4);
//change format to month date,year
let created = taken.slice(0, 6) + ',' + taken.slice(6);
let context = {
link: "https://www.instagram.com/p/" + node
.shortcode + "/",
image_url: node.display_url,
countLikes: node.edge_liked_by.count,
caption: node.edge_media_to_caption.edges[0].node
.text,
created: created
};
let html = template(context);
$("#instagramFeed").append(html);
});
$('#instagramFeed').flickity({
cellAlign: 'left',
wrapAround: true,
pageDots: false,
setGallerySize: false,
prevNextButtons: true,
arrowShape: { "x0": 20, "x1": 60, "y1": 40, "x2": 60, "y2": 35, "x3": 25 }
});
}
});
});
})(jQuery);
</script>

How can I create a different word for each player at the same time in vue js?

I have two players when I click the One Player button I want to disable the keyboard of player two, same with Two Player button. Each turn, they can only guess the word one of the time. It must different word for every player to avoid hint or cheating when the player turns. My problem is both players have the same word can guess. When I guess the letter, both letters appear in the blank square. Can somebody help me with my problem?
<div id="app">
<!-- title bar / header -->
<div id="header">
<div id="header-title">
Hangman
</div>
</div>
<!-- canvas where hangman is drawn -->
<div id="board">
<canvas id="board-canvas"></canvas>
</div>
<!-- row of blank letters for the selected word -->
<div id="word">
<div class="word-blankletter" v-for="letter in wordDivs" v-cloak>{{ letter }}</div>
</div>
<!-- keyboard -->
<div id="keyboard">
<div v-for="row in letters" class="keyboard-row">
<letter-button v-for="letter in row" :letter="letter" :game-over="gameOver" :two-players="twoPlayers" :key="letter" #check="check(letter)" v-cloak></letter-button>
</div>
</div>
<div id="word">
<div class="word-blankletter" v-for="letter in wordDivs" v-cloak>{{ letter }}</div>
</div>
<div id="keyboard">
<div v-for="row in letters" class="keyboard-row">
<letter-button v-for="letter in row" :letter="letter" :game-over="gameOver" :two-players="twoPlayers" :key="letter" #check="check(letter)" v-cloak></letter-button>
</div>
</div>
<!-- 'one player' 'play again' 'two players' -->
<div id="buttons">
<button class="buttons-button" :class="{ orange: !twoPlayers }" #click="onePlayer">One Player</button>
<button id="playagain" class="buttons-button" :class="{ hidden: !gameOver }" #click="playAgain">Play Again</button>
<button class="buttons-button" :class="{ orange: twoPlayers }" #click="twoPlayer">Two Players</button>
</div>
</div>
<script type="text/javascript" src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
// random integer helper function
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// keyboard letter button component
Vue.component("letter-button", {
props: ["letter", "gameOver", "twoPlayers"],
template: "<button class='keyboard-row-letter' :id='letter' :disabled='disabled' #click='clicked()'>{{ letter }}</button>",
data: function() {
return {
disabled: false
};
},
// disable button on click, and send 'check' event to run check() in main vue instance
methods: {
clicked: function() {
this.disabled = true;
this.$emit("check");
}
},
watch: {
// disable all buttons on game over; re-enable all buttons on restart
gameOver: function(newValue) {
this.disabled = newValue;
},
// re-enable all buttons when a new two-player game is started
twoPlayers: function(newValue) {
this.disabled = false;
}
}
})
// main vue instance
var app = new Vue({
el: "#app",
data: {
// keyboard letters
letters: [
["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"],
["A", "S", "D", "F", "G", "H", "J", "K", "L"],
["Z", "X", "C", "V", "B", "N", "M"]
],
// words to choose from
words: [
"DOGS",
"CATS",
"MICE",
"HAWK"
],
// currentWord will be set to a random word from above list
currentWord: "",
// each element in this array is a letter in the word
wordDivs: [],
// to count the number of wrong guesses
guesses: 0,
gameOver: false,
lose: false,
twoPlayers: false,
// will be set to the canvas element in mounted()
canvas: "",
// will be set to the canvas 2d context
ctx: ""
},
methods: {
// draws the gallows
drawGallows: function(ctx) {
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
ctx.fillStyle = "#FF9800";
ctx.strokeStyle = "#FF9800";
ctx.beginPath();
// left side
ctx.moveTo(this.canvas.width / 10, this.canvas.height / 10);
ctx.lineTo(this.canvas.width / 10, this.canvas.height * 0.95);
// bottom side
ctx.lineTo(this.canvas.width * 0.8, this.canvas.height * 0.95);
// top side
ctx.moveTo(this.canvas.width / 10, this.canvas.height / 10);
ctx.lineTo(this.canvas.width * 0.4, this.canvas.height / 10);
// hanging notch
ctx.lineTo(this.canvas.width * 0.4, this.canvas.height / 5);
ctx.stroke();
ctx.closePath();
},
// fill this.wordDivs with empty strings to create the orange blanks
makeBlanks: function() {
for (var i = 0; i < this.currentWord.length; i++) {
this.wordDivs.push("");
}
},
// draws the appropriate part of the hanging man and/or 'game over'
updateCanvas: function(ctx) {
// this.drawGallows(ctx);
// draw the head
if (this.guesses === 0) {
ctx.beginPath();
ctx.arc(this.canvas.width * 0.4, (this.canvas.height / 5) + 20, 20, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();
}
// draw the torso
else if (this.guesses === 1) {
ctx.beginPath();
ctx.moveTo(this.canvas.width * 0.4, (this.canvas.height / 5) + 40);
ctx.lineTo(this.canvas.width * 0.4, this.canvas.height / 2);
ctx.stroke();
ctx.closePath();
}
// draw the right leg
else if (this.guesses === 2) {
ctx.beginPath();
ctx.moveTo(this.canvas.width * 0.4, this.canvas.height / 2);
ctx.lineTo((this.canvas.width * 0.4) + 30, this.canvas.height * 0.7);
ctx.stroke();
ctx.closePath();
}
// draw the left leg
else if (this.guesses === 3) {
ctx.beginPath();
ctx.moveTo(this.canvas.width * 0.4, this.canvas.height / 2);
ctx.lineTo((this.canvas.width * 0.4) - 30, this.canvas.height * 0.7);
ctx.stroke();
ctx.closePath();
}
// draw the right arm
else if (this.guesses === 4) {
ctx.beginPath();
ctx.moveTo(this.canvas.width * 0.4, (this.canvas.height / 5) + 55);
ctx.lineTo((this.canvas.width * 0.4) + 35, (this.canvas.height / 2) + 10);
ctx.stroke();
ctx.closePath();
}
// draw the left arm and handle game over
else if (this.guesses === 5) {
ctx.beginPath();
ctx.moveTo(this.canvas.width * 0.4, (this.canvas.height / 5) + 55);
ctx.lineTo((this.canvas.width * 0.4) - 35, (this.canvas.height / 2) + 10);
ctx.stroke();
ctx.closePath();
// game over
ctx.font = "24px Roboto, sans-serif";
ctx.fillText("Game Over", this.canvas.width * 0.4 - 30, this.canvas.height * 0.9);
this.gameOver = true;
this.lose = true;
// fill in the word with the correct answer
for (var i = 0; i < this.currentWord.length; i++) {
Vue.set(this.wordDivs, i, this.currentWord[i]);
}
}
this.guesses++
},
// check the chosen letter when a letter component emits 'check'
check: function(letter) {
if (!this.gameOver) {
var guessCorrect = false;
// check if the letter is in the word, if so, fill it in
for (var i = 0; i < this.currentWord.length; i++) {
if (letter == this.currentWord[i]) {
Vue.set(this.wordDivs, i, letter);
guessCorrect = true;
}
}
// if there are no more blanks in the word, you win
if (!this.wordDivs.some(function(value) {return value == ""})) {
this.gameOver = true;
this.ctx.font = "24px Roboto, sans-serif";
this.ctx.fillText("You Win!", this.canvas.width * 0.4 - 30, this.canvas.height * 0.9);
}
// if they guess wrong, draw the man
if (!guessCorrect) {
this.updateCanvas(this.ctx);
}
}
},
// re-initializes the game
restart: function() {
this.gameOver = false;
this.lose = false;
this.guesses = 0;
this.wordDivs.splice(0);
this.drawGallows(this.ctx);
this.makeBlanks();
},
// resets the game to one-player mode and chooses a new word
onePlayer: function() {
if (this.twoPlayers) {
this.twoPlayers = false;
this.currentWord = this.words[randomInteger(0, this.words.length - 1)];
this.restart();
}
},
// starts two-player mode and prompts the user to enter a word
twoPlayer: function() {
if (this.twoPlayers) {
this.twoPlayers = false;
this.currentWord = this.words[randomInteger(0, this.words.length - 1)];
this.restart();
}
},
// chooses a new word and resets the game when 'play again' is clicked
playAgain: function() {
if (this.twoPlayers) {
this.currentWord = this.words[randomInteger(0, this.words.length - 1)];
}
else {
this.currentWord = this.words[randomInteger(0, this.words.length - 1)];
}
this.restart();
}
},
// identify the canvas element and initialize it, draw the gallows, choose a word, and draw the blanks.
mounted: function() {
this.canvas = document.getElementById("board-canvas");
this.canvas.width = document.getElementById("board").offsetWidth;
this.canvas.height = document.getElementById("board").offsetHeight;
this.ctx = this.canvas.getContext("2d");
this.ctx.lineWidth = 2;
this.drawGallows(this.ctx);
this.currentWord = this.words[randomInteger(0, this.words.length - 1)];
this.makeBlanks();
}
});

Dynamically update lines in Highcharts time series chart

Here I'm working on Highcharts time series chart with live streaming data, based on the sample jsfiddle. In the fiddle there shows 4 lines named as input1, input2, input3, & input 4 and it is updated with live random data but in my actual project the input values are updated via MQTT. In actual project, sometimes, when we push streaming data, there will be increase or decrease in no: of inputs (such as input5, input6 like wise). So how can we add new line or remove line dynamically in time series chart with streaming data.
javascript code :
$(function() {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series;
var length = series.length;
setInterval(function() {
var x = (new Date()).getTime(), // current time
a0 = Math.random();
a1 = Math.random();
a2 = Math.random();
series[0].addPoint([x, Math.random()], true, true);
for (var i = 1; i < length; i++) {
series[i].addPoint([x, Math.random()], false, true);
}
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
legend: {
enabled: true
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
exporting: {
enabled: false
},
series: [{
name: 'input1',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'input2',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'input3',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'input4',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});

KineticJs-how to update x and y position of the multiple images after resizing the stage layer

As I am new to KineticJs so, I have tried implementing the functionality using Kinectic js for drawing the multiple image on different- different x and y. Now I wanted to resize the stage layer or canvas. I have done that by using the code given below
window.onresize = function (event) {
stage.setWidth(($('#tab' + tabId).innerWidth() / 100) * 80);
var _images = layer.getChildren();
for (var i = 0; i < _images.length; i++) {
if (typeof _images[i].getId() != 'undefined') {
//alert(stage.getScale().x);
_images[i].setX(_images[i].getX() * stage.getScale().x);
layer.draw();
}
}
}
but now the problem is the are being defined and now if browser resize than stage is resized but the images on the prev x and y are fixed . I would like to keep them fixed on the position on resizing of stage layer or canvas.Here are the link of the image before resize and after resizing.beforeresize and afterResize .
Here is my entire code given below:-
$("#tabs li").each(function () {
$(this).live("click", function () {
clearInterval(_timer);
var tabname = $(this).find("a").attr('name');
tabname = $.trim(tabname.replace("#tab", ""));
var tabId = $(this).find("a").attr('href');
tabId = $.trim(tabId.replace("#", ""));
$.ajax({
url: "/Home/GetTabsDetail",
dataType: 'json',
type: 'GET',
data: { tabId: tabId },
cache: false,
success: function (data) {
var bayStatus = [];
var i = 0;
var image_array = [];
var BayExist = false;
var BayCondition;
var imgSrc;
var CanvasBacgroundImage;
var _X;
var _bayNumber;
var _Y;
var _ZoneName;
$(data).each(function (i, val) {
i = i + 1;
if (!BayExist) {
bayStatus = val.BayStatus;
CanvasBacgroundImage = val.TabImageLocation;
BayExist = true;
}
$.each(val, function (k, v) {
if (k == "BayNumber") {
BayCondition = bayStatus[v];
_bayNumber = v;
if (BayCondition == "O")
imgSrc = "../../images/Parking/OccupiedCar.gif"
else if (BayCondition == "N")
imgSrc = "../../images/Parking/OpenCar.gif";
}
if (k == "BayX")
_X = v;
if (k == "BayY")
_Y = v;
if (k == "ZoneName")
_ZoneName = v;
});
image_array.push({ img: imgSrc, xAxis: _X, yAxis: _Y, toolTip: _bayNumber, ZoneName: _ZoneName });
});
var imageUrl = CanvasBacgroundImage;
if ($('#tab' + tabId).length) {
// $('#tab' + tabId).css('background-image', 'url("../../images/Parking/' + imageUrl + '")');
var stage = new Kinetic.Stage({
container: 'tab' + tabId,
width: ($('#tab' + tabId).innerWidth() / 100) * 80, // 80% width of the window.
height: 308
});
window.onresize = function (event) {
stage.setWidth(($('#tab' + tabId).innerWidth() / 100) * 80);
}
$('#tab' + tabId).find('.kineticjs-content').css({ 'background-image': 'url("../../images/Parking/' + imageUrl + '")', 'background-repeat': ' no-repeat', 'background-size': '100% 100%' });
var layer = new Kinetic.Layer();
var planetOverlay;
function writeMessage(message, _x, _y) {
text.setX(_x + 20);
text.setY(_y + 1);
text.setText(message);
layer.draw();
}
var text = new Kinetic.Text({
fontFamily: 'Arial',
fontSize: 14,
text: '',
fill: '#000',
width: 200,
height: 60,
align: 'center'
});
var opentooltip = new Opentip(
"div#tab" + tabId, //target element
"dummy", // will be replaced
"", // title
{
showOn: null // I'll manually manage the showOn effect
});
Opentip.styles.win = {
borderColor: "black",
shadow: false,
background: "#EAEAEA"
};
Opentip.defaultStyle = "win";
// _timer = setInterval(function () {
for (i = 0; i < image_array.length; i++) {
img = new Image();
img.src = image_array[i].img;
planetOverlay = new Kinetic.Image({
x: image_array[i].xAxis,
y: image_array[i].yAxis,
image: img,
height: 18,
width: 18,
id: image_array[i].toolTip,
name: image_array[i].ZoneName
});
planetOverlay.on('mouseover', function () {
opentooltip.setContent("<span style='color:#87898C;'><b>Bay:</b></span> <span style='color:#25A0D3;'>" + this.getId() + "</span><br> <span style='color:#87898C;'><b>Zone:</b></span><span style='color:#25A0D3;'>" + this.getName() + "</span>");
//writeMessage("Bay: " + this.getId() + " , Zone: " + this.getName(), this.getX(), this.getY());//other way of showing tooltip
opentooltip.show();
$("#opentip-1").offset({ left: this.getX(), top: this.getY() });
});
planetOverlay.on('mouseout', function () {
opentooltip.hide();
// writeMessage('');
});
planetOverlay.createImageHitRegion(function () {
layer.draw();
});
layer.add(planetOverlay);
layer.add(text);
stage.add(layer);
}
// clearInterval(_timer);
//$("#tab3 .kineticjs-content").find("canvas").css('background-image', 'url("' + imageUrl + '")');
// },
// 500)
}
}
,
error: function (result) {
alert('error');
}
});
});
});
I want to keep the icons on the position where they were before resizing. I have tried but could not get the right solution to get this done.
How can How can I update x,y position for the images . Any suggestions would be appreciated.
Thanks is advance.
In window.resize, you're changing the stage width by a scaling factor.
Save that scaling factor.
Then multiply the 'x' coordinate of your images by that scaling factor.
You can reset the 'x' position of your image like this:
yourImage.setX( yourImage.getX() * scalingFactor );
layer.draw();
In the above mentioned code for window.onresize. The code has been modified which as follow:-
window.onresize = function (event) {
_orignalWidth = stage.getWidth();
var _orignalHeight = stage.getHeight();
// alert(_orignalWidth);
// alert($('#tab' + tabId).outerHeight());
stage.setWidth(($('#tab' + tabId).innerWidth() / 100) * 80);
//stage.setHeight(($('#tab' + tabId).outerHeight() / 100) * 80);
_resizedWidth = stage.getWidth();
_resizedHeight = stage.getHeight();
// alert(_resizedWidth);
_scaleFactorX = _resizedWidth / _orignalWidth;
var _scaleFactorY = _resizedHeight / _orignalHeight;
//alert(_scaleFactor);
var _images = layer.getChildren();
for (var i = 0; i < _images.length; i++) {
if (typeof _images[i].getId() != 'undefined') {
//alert(stage.getScale().x);
_images[i].setX(_images[i].getX() * _scaleFactorX);
//_images[i].setY(_images[i].getY() * _scaleFactorY);
layer.draw();
}
}
}