html5 canvas script looping font - loops

<html>
<body>
<canvas id=cvs width=400px height=400px />
</body>
<script>
var text = document.getElementById('cvs').getContext('2d');
var x = 30;
for(var j=0, k='a'; j<3; j++,k++;)
{
text.fillStyle='#000';
text.font="30px Arial";
text.fillText(k,x,30);
x=x+60;
}
</script>
</html>
the k values contains font..
then i try to print the k values 3times, but it shown "a, NaN, NaN"
please help me to get the loop of font.. thanks a lot~

There is no char-Type in JavaScript. Use .charCodeAt(0) at the String-Object "a" to get the char code and use String.fromCharCode(...) to convert the char code back to a String.
Besides: HTML-Arguments have to be quoted and width and height take no units. Units are css only!
Besides (2): There is an additional ; in your for.
<html>
<body>
<canvas id="cvs" width="400" height="400" />
</body>
<script>
var text = document.getElementById('cvs').getContext('2d');
var x = 30;
for (var j=0, k="a".charCodeAt(0); j<3; j++,k++)
{
text.fillStyle='#000';
text.font="30px Arial";
text.fillText(String.fromCharCode(k),x,30);
x=x+60;
}
</script>
</html>

Related

Is it possible to create an array list of objects in p5JavaScript?

I'm currently working on a Stacked Bar Chart Demo using p5JavaScript as you can see in the Code Snippet Below.
Basically, I want to have 2 series of data on X&Y Axis :
1) An array of numbers (var)
and
2) An Array-List of variables (var1,var2,var3,...).
The only reference I found for this is the link provided below:
https://sites.google.com/site/processingp5js/data-structures/arraylist
If somebody know how to create a "Class of Objects" or an Array-List please let me know.
The Script is shown below :
//REFERENCES:
// https://sites.google.com/site/processingp5js/data-structures/arraylist
/* Needed Variables Declaration */
var arrayOfMonths = ["dd/mm/yy","dd/mm/yy","dd/mm/yy","dd/mm/yy","dd/mm/yy","dd/mm/yy","dd/mm/yy","dd/mm/yy","dd/mm/yy","dd/mm/yy"];
var arrayOfResponses = ["num","num","num","num","num","num","num"];
/* Calculated Variables */
var numOfMonths = arrayOfMonths.length;
var numOfResponses = arrayOfResponses.length;
/* Variables Declaration */
var canvasWidth = numOfMonths * 100;
var canvasHeight = numOfResponses * 100;
function setup() {
createCanvas(canvasWidth, canvasHeight);
}
function draw() {
background(255); //White Background Color
chartBase(); //Add X,Y Axis
addPointers(numOfResponses, numOfMonths); //Add Pointers
addTextToPointers(); //Add Text to pointers
//addValues(); //Add the Bars (Values) of the Chart
}
function chartBase(){
/* DRAW X AXIS */
line(canvasWidth-(canvasWidth-50), canvasHeight-100,
(canvasWidth-50)+25, canvasHeight-100);
/* DRAW Y AXIS */
line(canvasHeight-(canvasHeight-100),canvasHeight-(canvasHeight-50)-25,
canvasHeight-(canvasHeight-100),canvasHeight-50);
}
function addPointers(numOfResponses, numOfMonths){
var spaceBetweenX = canvasWidth - (canvasWidth-150);
var spaceBetweenY = canvasHeight- 150;
/* ADD POINTERS TO X AXIS */
for(var x=0; x<numOfMonths; x++){
ellipse(spaceBetweenX,canvasHeight-100,10,10);
spaceBetweenX += canvasWidth/numOfMonths;
}
/* ADD POINTERS TO Y AXIS */
for(var y=0; y<numOfResponses; y++){
ellipse(canvasWidth-(canvasWidth-100), spaceBetweenY, 10, 10);
spaceBetweenY -= canvasHeight/numOfResponses;
}
}
function addTextToPointers(){
var spaceBetweenX = canvasWidth-(canvasWidth-125);
var spaceBetweenY=(canvasHeight-100)-50;
textSize(13);
/* ADD TEXT TO X AXIS */
for(var x=0; x<numOfMonths; x++){
var currentText = arrayOfMonths[x];
text(currentText, spaceBetweenX, (canvasHeight-75));
spaceBetweenX+=canvasWidth/numOfMonths;
}
/* ADD TEXT TO Y AXIS */
for(var y=0; y<numOfResponses; y++){
var currentText = arrayOfResponses[y];
text(currentText, (canvasWidth-(canvasWidth-60)), spaceBetweenY);
spaceBetweenY -= canvasHeight/numOfResponses;
}
}
html, body {
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
Just use an array.
Arrays in JavaScript act a lot like the ArrayList class in Java or Processing. Their size can change, and you can dynamically add or remove elements from them.
Check out W3Schools or MDN for tutorials on arrays in JavaScript, or just google "javascript arrays" for a ton of results.

Angular: How to get each symbol from array n times in random order?

I have the array with symbols A-E
I need to output each symbol in ng-repeat, but array should be in random order and each symbol should be displayed n times (for example 4 times)
You can use the Array.prototype.sort() method to shuffle your array.
I created a function that you can pass as parameters the initial array and the times that you want to sort it, as below:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function($scope) {
function randomize(array, times) {
var temp = [];
for (var i = 0; i < times; i++) {
array.sort(function() {
return .5 - Math.random();
});
temp = temp.concat(array);
}
return temp;
}
$scope.symbols = randomize(['a', 'b', 'c', 'd', 'e'], 4);
});
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
Words:
<div ng-repeat="symbol in symbols track by $index" ng-bind="symbol">
</div>
</body>
</html>
You ll probably need two functions, one to shuffle the symbols and other to set a array 'N' times with shuffling.
To Set it :
var num = 5; // 'N' time shuffling.
function setArray() {
for(var i = 0; i < num; i++) {
$scope.symbols = $scope.symbols.concat(shuffle());
}
}
setArray();
here shuffle() is another function to select a random order of the symbols.
See DEMO here.
OK, since the other suggestions were just so complicated, I'll build out from my comment.
var result = [];
for (var i=0; i<4; i++) {
for (var j=0; j<yourArray.length; j++) {
var newIndex = Math.floor(Math.random() * result.length);
result[newIndex] = yourArray[i];
}
}
You could probably even make a filter from this.

bind nested ng-repeat to model

In the following example, I should ask for the name of six students. They will be grouped according to bedroom type.
2 -> double
1 -> single
3 -> tiple
So, it means that I'll have a array of students (6 students). I would like to get their names. I was trying to create a variable like 'count' and put as ng-model of the input and increment during the loop, but it didn't work.
full html:
<!doctype html>
<html ng-app="sampleApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller='SampleController'>
<div ng-repeat='i in numberOfAccommodations track by $index'>
Bedroom {{$index}}
<span ng-repeat='x in numberOfStudents[$index]'>
Student {{$index}}
<input type='text' ng-model='abroadStudents[???].name' /> <!-- this input to student model -->
</span>
</div>
<input type='button' value='test' ">
<script>
angular.module('sampleApp',[]).controller('SampleController',function($scope){
$scope.abroadStudents = new Array[6];
$scope.abroadAccommodation = new Array();
$scope.abroadAccommodation.push({ "bedroomType": 2}, { "bedroomType": 1 }, {"bedroomType": 3});
$scope.numberOfAccommodations = function()
{
var arr = new Array();
for (var i = 0 ; i < $scope.abroadAccommodation.length ; i++)
{
arr.push(i);
}
return arr;
}();
$scope.numberOfStudents = function()
{
var arr = new Array();
for (var x = 0 ; x < $scope.abroadAccommodation.length ; x++)
{
var temp = 0;
var intArr = new Array();
do
{
intArr.push(temp);
temp++;
}
while(temp < $scope.abroadAccommodation[x].bedroomType);
arr.push(intArr);
}
return arr;
}();
});
</script>
</body>
</html>
I rewrote your logic to create a more logical structure of objects which does not require relying upon the $index. It creates an Array of room objects, then iterates through the array of abroadAccommodation. For each abroadAccommodation, it adds a room, and based on type, adds the appropriate number of student objects. It is then very easy to use ng-repeat to iterate through each room to identify each student.
Note I also am using angular.forEach here.
<!doctype html>
<html ng-app="sampleApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller='SampleController'>
<div ng-repeat="room in rooms">
{{room.roomNum}}
<div ng-repeat="student in room.students">
{{student.bed}}
<input ng-model="student.name" />
</div>
</div>
Student List:
<div ng-repeat="room in rooms">
<div ng-repeat="student in room.students">
{{student.name}}
</div>
</div>
<script>
angular.module('sampleApp', []).controller('SampleController', function($scope) {
$scope.abroadAccommodation = new Array();
$scope.abroadAccommodation.push({
"bedroomType ": 2
}, {
"bedroomType ": 1
}, {
"bedroomType ": 3
});
$scope.rooms = function() {
var arr = [];
angular.forEach($scope.abroadAccommodation, function(type, count) {
var room = {
"roomNum": "room " + (count + 1),
students: []
};
angular.forEach(type, function(numBeds) {
for (i = 0; i < numBeds; i++) {
room.students.push({
"bed": "bed " + (i + 1),
"name": "student" + Math.random()
});
}
arr.push(room);
})
});
return arr;
}();
});
</script>
</body>
</html>
http://plnkr.co/edit/YaPo54NUBPk9AnZkGcCc?p=preview

AngularJS NG-CSV files not downloading

I am fairly new to AngularJS, i am trying to generate .csv files from an Array using ng-csv.
Now i have tried everything but the files are not generated, i even tried the most simple example i could see on the internet.
I do not see any errors in the error console but still no files are generated.
I am working under windows with XAMPP.
<!DOCTYPE html>
<html ng-app="APP">
<head>
<meta charset="UTF-8">
<title>angular-count-to example</title>
<style type="text/css">
.element{cursor:pointer;float:left;background-color:#ccc;padding:4px;}
</style>
</head>
<body ng-controller="ExampleController">
<p>{{data}}</p>
<button type="button" ng-csv="data" filename="test.csv">Export</button>
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script type="text/javascript" src="bower_components/ng-csv/src/ng-csv/ng-csv.js"></script>
<script>
angular.module('APP',["ngSanitize","ngCsv"]).
controller('ExampleController', function ($scope) {
$scope.filename = "test";
$scope.data = [{a: 1, b:2}, {a:3, b:4}];
});
</script>
</body>
</html>
Above is the simplest example i tried, however even this is not working.
Try out a pure HTML5 Solution. This was a code block i did a while ago. Try customizing for yourself by excluding useless paramaters
function (JSONData, ReportTitle, ShowLabel, reportType, reportName) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
angular.forEach(arrData, function (data, index) {
if (data.date != undefined)
data.date = dateFormat(data.date)
});
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
row += index + ';';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
//var temp = arrData[i][index].toString().replace('.', ',');
//arrData[i][index] = temp;
row += '"' + arrData[i][index] + '";';
}
row = row.split('.').join(",");
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g, "_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
It looks like you are linking to the wrong ng-csv.js. The ng-csv.js file in the bower_components/ng-csv/src/ng-csv/ folder doesn't contain all of the code, you need to use the build version. Try this:
<script type="text/javascript" src="bower_components/ng-csv/build/ng-csv.js"></script>

Angular Smart table + add summary rows

I want to add summary row in Angular smart-table. The rows should not be sorted and it should be added in last.
I had tried but unable to achieve that, and I've searched a lot but was unable to find more information on Google.
Can anyone please let me know what should be the approach to add a summary row?
This kind of sorting can be done using custom sorting algorithm,by adding the same in sortAlgorithm under globalConfig (see smart-table documentation).
try this,
In html,
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link data-require="bootstrap-css#3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script data-require="angular.js#1.2.17" data-semver="1.2.17" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="smart-table.debug.js"></script>
</head>
<body ng-controller="mainCtrl">
<h1>{{greetings}} Plunker!</h1>
<smart-table config="globalConfig" columns="columnsConfig" rows="items"></smart-table>
</body>
</html>
In js file,
angular.module('myApp',['smartTable.table'])
.controller('mainCtrl',['$scope',function(scope,$filter){
scope.greetings="world";
scope.items=[
{name:'mahesh',salary:10000,},
{name:'sachin',salary:15000},
{name:'varun',salary:12000},
{name:'vijay',salary:11000},
{name:'prem',salary:12500},
{name:'gandhi',salary:13000},
{name:'sathish',salary:14500},
{name:'ram',salary:20000},
{name:'siva',salary:22000},
{name:'dilli',salary:18000}
];
var i=0;
scope.totalSalary=0;
scope.calSalary=function(){
for(i=0;i<scope.items.length;i++){
scope.totalSalary=scope.totalSalary+scope.items[i].salary;
}
return scope.totalSalary;
}
var temp={name:'total',salary:scope.calSalary()};
scope.items.push(temp);
scope.globalConfig={
isPaginationEnabled:false,
selectionMode:'single',
sortAlgorithm:function customSortAlgorithm(arrayRef, sortPredicate, reverse) {
var i=0;
var sortTemp='';
var n=arrayRef.length-1;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if(sortPredicate==='salary'){
switch(reverse) {
case true:
if (arrayRef[i].salary > arrayRef[(j)].salary)
{
sortTemp=arrayRef[i];
arrayRef[i]=arrayRef[j];
arrayRef[j]=sortTemp;
}
break;
case false:
if (arrayRef[i].salary < arrayRef[(j)].salary)
{
sortTemp=arrayRef[i];
arrayRef[i]=arrayRef[j];
arrayRef[j]=sortTemp;
}
break;
default:
}}
if(sortPredicate==='name'){
switch(reverse) {
case true:
if (arrayRef[i].name > arrayRef[(j)].name)
{
sortTemp=arrayRef[i];
arrayRef[i]=arrayRef[j];
arrayRef[j]=sortTemp;
}
break;
case false:
if (arrayRef[i].name < arrayRef[(j)].name)
{
sortTemp=arrayRef[i];
arrayRef[i]=arrayRef[j];
arrayRef[j]=sortTemp;
}
break;
default:
}}
}
}
return arrayRef;
}
};
scope.columnsConfig=[
{label:'name',map:'name'},
{label:'salary',map:'salary'}
];
}]);
Please have a look at this plunker for the same.
Hope this solves your problem :)

Categories

Resources