function setup() { document.getElementById('canvas').addEventListener('mousemove',onMouseMove); document.getElementById('canvas').addEventListener('keydown',onKeyDown); } function onMouseMove(event) { var posx = event.clientX; var posy = event.clientY; console.log("(", posx, ", ", posy, ")"); } function onKeyDown(event) { var keyID = event.keyID; console.log("ID: ", keyID); }
Category: JavaScript
jasmine
javascript test library
https://jasmine.github.io/
describe('Address Book', function(){ it('should be able to add a contact', function(){ var addressBook = new AddressBook(), thisContact = new Contact(); addressBook.addContact(thisContact); expect(addressBook.getContact(0)).toBe(thisContact); }); });
describe('Address Book', function(){ it('should be able to add a contact', function(){ var addressBook = new AddressBook(), thisContact = new Contact(); addressBook.addContact(thisContact); expect(addressBook.getContact(0)).toBe(thisContact); }); it('should be able to delete a contact', function(){ var addressBook = new AddressBook(), thisContact = new Contact(); addressBook.addContact(thisContact); addressBook.deleteContact(0); expect(addressBook.getContact(0)).not.toBeDefine(); }); });
function
var amy = {loc:1}; move(amy); var ben = {loc:9}; move(ven);
var move = function(car){ car.loc++; };
object create
var gold = {a:1}; var blue = extend({}, gold); var rose = Object.create(gold); gold.z = 3 log(blue.z); //undefined log(rose.z); //3
var = {}
this indicate in memory variable.
gulp sass
npm install gulp-sass
var gulp = require('gulp'); gulp.task('default', function(){ console.log("hello, gulp!"); }); gulp.task('styles', function(){ gulp.src('sass/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./css')); }); gulp.task('default', function(){ gulp.watch('sass/**/*.scss',['styles']); });
Linting is the process of running a program that will analyse code for potential errors.
ESLint
[vagrant@localhost rss24]$ sudo npm install -g eslint
span:inline
div:block
parameter
?name=value
fragment
#fragment
Uppercase
function inName(name){ name = name.trim().split(" "); name[1] = name[1].toUpperCase(); name[0] = name[0].slice(0,1).toUpperCase() + name[0].slice(1).toLowerCase(); return name[0] + " "+name[1]; }
json
JavaScript Object Notation. JSON is a popular and simple format for storing and transferring nested or hierarchal data. It’s so popular that most other programming languages have libraries capable of parsing and writing JSON (like Python’s JSON library). Internet GET and POST requests frequently pass data in JSON format. JSON allows for objects (or data of other types) to be easily encapsulated within other objects.
var education = { "scool": [ { "name": "Echerd College", "city": "Saint Petersburg, FL, US", "degree": "BA", "major": ["compSci", "French"] }, { "name": "Nova Southeastern University", "city": "Fort Lauderdale, FL, US", "degree": "Masters", "major": ["compSci"] }, ] };
validate json : http://jsonlint.com/
if (document.getElementsByClassName("education-entry").length === 0) { document.getElementById("education").style.display = "none"; }
for in loop
for(item in object){ console.log(contry); }
click
$(document).click(function(loc){ var x = loc.pageX; var y = loc.pageY; logClicks(x,y); });
var work = { "jobs": [ { "employer": "Udacity", "title": "Course Developer", "location": "Mountain View, CA", "dates": "Feb 2014 - Current", "description": "Who moved my cheese cheesy feet cauliflower cheese. Queso taleggio when the cheese comes out everybody's happy airedale ricotta cheese and wine paneer camembert de normandie. Swiss mozzarella cheese slices feta fromage frais airedale swiss cheesecake. Hard cheese blue castello halloumi parmesan say cheese stinking bishop jarlsberg." }, { "employer": "LearnBIG", "title": "Software Engineer", "location": "Seattle, WA", "dates": "May 2013 - Jan 2014", "description": "Who moved my cheese cheesy feet cauliflower cheese. Queso taleggio when the cheese comes out everybody's happy airedale ricotta cheese and wine paneer camembert de normandie. Swiss mozzarella cheese slices feta fromage frais airedale swiss cheesecake. Hard cheese blue castello halloumi parmesan say cheese stinking bishop jarlsberg." }, { "employer": "LEAD Academy Charter High School", "title": "Science Teacher", "location": "Nashville, TN", "dates": "Jul 2012 - May 2013", "description": "Who moved my cheese cheesy feet cauliflower cheese. Queso taleggio when the cheese comes out everybody's happy airedale ricotta cheese and wine paneer camembert de normandie. Swiss mozzarella cheese slices feta fromage frais airedale swiss cheesecake. Hard cheese blue castello halloumi parmesan say cheese stinking bishop jarlsberg." }, { "employer": "Stratford High School", "title": "Science Teacher", "location": "Nashville, TN", "dates": "Jun 2009 - Jun 2012", "description": "Who moved my cheese cheesy feet cauliflower cheese. Queso taleggio when the cheese comes out everybody's happy airedale ricotta cheese and wine paneer camembert de normandie. Swiss mozzarella cheese slices feta fromage frais airedale swiss cheesecake. Hard cheese blue castello halloumi parmesan say cheese stinking bishop jarlsberg." } ] }; // Your code goes here! Let me help you get started function locationizer(work_obj) { var locationArray = []; for(job in work_obj.jobs){ var newLocation = work_obj.jobs[job].location; locationArray.push(newLocation); } return locationArray; }
javascript intro
$(“#main”).append(“[name]”);
var email = "cameron@email.com"; var newEmail = email.replace("email.com","gmail.com"); console.log(email); console.log(newEmail); var formattedName = HTMLheaderName.replace("%data%", name); $("#header").append(formattedName)
The prepend() method inserts specified content at the beginning of the selected elements.
var formattedName = HTMLheaderName.replace("%data%", name); var role = "web developer"; var formattedRole = HTMLheaderRole.replace("%data%", role); $("#header").prepend(formattedName); $("#header").prepend(formattedRole);
var s = “audacity”;
s = s[1].toUpperCase() + s.slice(2);
var sampleArray = [0,0,7]; var incrementLastArrayElement = function(_array) { var newArray = []; newArray = _array.slice(0); var lastNumber = newArray.pop(); newArray.push(lastNumber + 1); return newArray; }; console.log(incrementLastArrayElement(sampleArray));
object
var bio = { "name":"john doe", "role":"web developer", "contacts":{ "mobile":"080-1234-5678", "email": "john@example.com", "github":"hohndoe", "twitter": "@johndoe", "location": "San Francisco" }, "welcomeMessage": "testtesttest", "skills": [ "awsomenss", "delivering things", "cryogenic sleep", "saving universe" ], "bioPic": "images/fry.jpg" }
object model
var work = {}; work.position = "web development"; work.employer = "more than 1000"; work.years = "0"; work.city = "yurakucho"; var education = {}; education["name"] = "nova southern university" education["years"] = "2005-2013" education["city"] = "fort lauderdale, fl, us" $("#main").append(work.position); $("#main").append(education.name);
迷路
左上を迷路のスタート地点、右下を迷路のゴール地点とし、0と1の配列で道と壁を作成しています。迷路作成のアルゴリズムは、棒倒し法で記載しています。考えた人は天才ですね。。
棒倒し法
1.一つとびに壁を作る 1れつ目の棒を上下左右のどちらかに倒す
2.2列目以降の棒を左以外のどれかに倒す
00010
11010
00000
01011
01000
どの位置を0から1に変更するかは、以下のように記載します。
var points = [
[0, -1],
[0, 1],
[1, 0],
[-1, 0],
];
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>MAZE</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="styles.css"> <style> body { font-family: "Century Gothic"; font-size: 16px; } #container { text-align: center; margin: 20px auto; } #mycanvas { background: #AAEDFF; } .btn { margin: 3px auto; width: 200px; padding: 5px; background: #00AAFF; color: #ffffff; border-radius:3px; cursor: pointer; } .btn:hover{ opacity: 0.8; } </style> </head> <body> <div id="container"> <canvas width="100" height="100" id="mycanvas"> Canvasに対応したブラウザを用意してください。 </canvas> <div id="reset" class="btn">RESET</div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> (function(){ var Maze = function(col, row){ this.map = []; this.col = col; this.row = row; this.startX = 0; this.startY = 0; this.goalX =col - 1; this.goalY =row - 1; this.points = [ [0, -1], [0, 1], [1, 0], [-1, 0], ]; this.rand = function(n) { return Math.floor(Math.random() * (n + 1)); }; this.init = function() { for (var x = 0; x < col; x++) { this.map[x] = []; for (var y = 0; y < row; y++) { this.map[x][y] = 0; } } for (var x = 1; x < col; x += 2) { for (var y = 1; y < row; y += 2) { this.map[x][y] = 1; } } for (var x = 1; x < col; x += 2) { for (var y = 1; y < row; y += 2) { do { if (x === 1) { // 上下左右に倒す var r = this.points[this.rand(3)]; } else { // 左以外に倒す var r = this.points[this.rand(2)]; } } while (this.map[x + r[0]][y + r[1]] === 1); this.map[x + r[0]][y + r[1]] = 1; } } }; this.draw = function() { var view = new View(); view.draw(this); }; }; var View = function(){ this.wallSize = 10; this.wallColor = '#3261AB'; this.routeColor = '#ff0088'; this.canvas = document.getElementById('mycanvas'); if (!this.canvas || !this.canvas.getContext){ return false; } this.ctx = this.canvas.getContext('2d'); this.draw = function(maze){ this.canvas.width = (maze.col + 2) * this.wallSize; this.canvas.height = (maze.row + 2) * this.wallSize; // 上下の壁 for (var x = 0; x < maze.col + 2; x++) { this.drawWall(x, 0); this.drawWall(x, maze.row + 1); } // 左右の壁 for (var y = 0; y < maze.row + 2; y++) { this.drawWall(0, y); this.drawWall(maze.col + 1, y); } // 迷路の内部 for (var x = 0; x < maze.col; x++){ for(var y = 0; y < maze.row; y++){ if(maze.map[x][y] === 1){ this.drawWall(x + 1, y + 1); } if ((x === maze.startX && y === maze.startY) || (x === maze.goalX && y === maze.goalY)) { this.drawRoute(x + 1, y + 1); } } } }; this.drawWall = function(x, y) { this.ctx.fillStyle = this.wallColor; this.drawRect(x, y); }; this.drawRoute = function(x, y) { this.ctx.fillStyle = this.routeColor; this.drawRect(x, y); }; this.drawRect = function(x, y){ this.ctx.fillRect( x * this.wallSize, y * this.wallSize, this.wallSize, this.wallSize); }; }; function reset(){ var maze = new Maze(13, 13); maze.init(); maze.draw(); } reset(); document.getElementById('reset').addEventListener('click', function(){ reset(); }); // // 迷路のデータを配列で用意 // // 0と1の配列で、1を壁と表現する ※奇数でないと道ができない // // canvasで描画 // // 棒倒し法 // // 一つとびに壁を作る 1れつ目の棒を上下左右のどちらかに倒す // // 2列目以降の棒を左以外のどれかに倒す // // 00010 // // 11010 // // 00000 // // 01011 // // 01000 // var map = []; // // map[0] = [0, 0, 0]; // // map[1] = [0, 1, 1]; // // map[2] = [0, 0, 0]; // var col = 13; // 奇数 // var row = 13; // 奇数 // for (var x = 0; x < col; x++){ // map[x] = []; // for (var y = 0; y < row; y++){ // map[x][y] = 0; // } // } // for (var x = 1; x < col; x += 2){ // for(var y = 1; y < row; y += 2){ // map[x][y] = 1; // } // } // var points = [ // [0, -1], // [0, 1], // [1, 0], // [-1, 0], // ]; // function rand(n){ // return Math.floor(Math.random() * (n + 1)); // } // for (var x = 1; x < col; x += 2){ // for(var y = 1; y < row; y += 2){ // map[x][y] = 1; // do { // if (x === 1){ // var r = points[rand(3)]; // } else { // var r = points[rand(2)]; // } // } while (map[x + r[0]][y + r[1]] === 1); // map[x + r[0]][y + r[1]] = 1; // } // } // var startX = 0; // var startY = 0; // var goalX =col - 1; // var goalY =row - 1; // var wallSize = 10; // var wallColor = '#3261AB'; // var routeColor = '#ff0088'; // var canvas = document.getElementById('mycanvas'); // if (!canvas || !canvas.getContext){ // return false; // } // var ctx = canvas.getContext('2d'); // canvas.width = (col + 2) * wallSize; // canvas.height = (row + 2) * wallSize; // // 上下の壁 // for (var x = 0; x < col + 2; x++) { // drawWall(x, 0); // drawWall(x, row + 1); // } // // 左右の壁 // for (var y = 0; y < row + 2; y++) { // drawWall(0, y); // drawWall(col + 1, y); // } // // 迷路の内部 // for (var x = 0; x < col; x++){ // for(var y = 0; y < row; y++){ // if(map[x][y] === 1){ // drawWall(x + 1, y + 1); // } // if ((x === startX && y === startY) || (x === goalX && y === goalY)) // { // drawRoute(x + 1, y + 1); // } // } // } // // 壁を描画 // function drawWall(x, y) { // ctx.fillStyle = wallColor; // drawRect(x, y); // } // function drawRoute(x, y) { // ctx.fillStyle = routeColor; // drawRect(x, y); // } // function drawRect(x, y){ // ctx.fillRect( // x * wallSize, // y * wallSize, // wallSize, // wallSize); // } })(); </script> </body> </html>
interactive Art
addEventListener(‘click’, function(e){})で、push(new Ball(x, y, r))します。ランダム関数の範囲をとる際には、return min + Math.floor(Math.random() * (max – min + 1))と書きます。また、ボールの移動は、x++, y++, バウンドは、x軸、y軸をそれぞれ-1をかけてあげます。
reference
.getBoundingClientRect():returns the size of an element and its position relative to the viewport.
setTimeout bind: http://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback
Object.prototype: property represents the Object prototype object.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Intractive Art</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> </style> </head> <body> <canvas id="mycanvas" width="500" height="250"> </canvas> <script> (function(){ 'use strict'; var canvas; var ctx; var Ball; var balls = []; var Stage; var stage; canvas = document.getElementById('mycanvas'); if (!canvas || !canvas.getContext) return false; ctx = canvas.getContext('2d'); function rand(min, max){ return min + Math.floor(Math.random() * (max - min + 1)); } function adjustPosition(pos, r, max) { /*if (x - r < 0) x = r; if (y - r < 0) y = r; if (x + r > canvas.width) x = canvas.width - r; if (y + r > canvas.height) y = canvas.height - r;*/ if (pos - r < 0){ return r; } else if (pos + r > max){ return max - r; } else { return pos; } } canvas.addEventListener('click', function(e){ var x, y, r; var rect; /*x = rand(100, 400); y = rand(100, 200);*/ rect = e.target.getBoundingClientRect(); x = e.clientX - rect.left; y = e.clientY - rect.top; r = rand(0, 100) < 20 ? rand(50, 80) : rand(10, 35); /*if (x - r < 0) x = r; if (y - r < 0) y = r; if (x + r > canvas.width) x = canvas.width - r; if (y + r > canvas.height) y = canvas.height - r;*/ x = adjustPosition(x, r, canvas.width); y = adjustPosition(y, r, canvas.height); balls.push(new Ball(x, y, r)); }); Ball = function(x, y, r){ this.x = x; this.y = y; this.r = r; this.vx = rand(-10, 10); this.vy = rand(-10, 10); this.color = 'hsla(' + rand(50, 100)+ ', ' + rand(40, 80) + '%, ' + rand(50, 60) +'%, ' + Math.random() + ')'; }; /*var ball = new Ball(rand(100, 200), rand(100, 200), rand(10, 50)); ball.draw();*/ Ball.prototype.draw = function(){ ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI*2); ctx.fillStyle = this.color; ctx.closePath(); ctx.fill(); }; Ball.prototype.move = function(){ if (this.x + this.r > canvas.width || this.x - this.r < 0){ this.vx *= -1; } if (this.y + this.r > canvas.height || this.y - this.r < 0){ this.vy *= -1; } this.x += this.vx; this.y += this.vy; }; Stage = function(){ this.update = function(){ var i; this.clear(); for (i = 0; i < balls.length; i++){ balls[i].draw(); balls[i].move(); } setTimeout(function(){ this.update(); }.bind(this), 30); }; this.clear = function(){ ctx.fillStyle = "#ecf0f1"; ctx.fillRect(0, 0, canvas.width, canvas.height); } }; stage = new Stage(); stage.update(); })(); </script> </body> </html>