D3.js

D3.jsはData Driven Documentの略です。

D3.js

d3.jsのライブラリです。

<script src="https://d3js.org/d3.v4.min.js"></script>

要素を指定して、命令を書いていきます。

      <script src="https://d3js.org/d3.v4.min.js"></script>
      <script>
      d3.select("body").selectAll("p").text("hello from d3");

      </script>

繋げて書くこともできます。

var p = d3.select("body").selectAll("p");
      p.text("hello from d3");
      p.style("font-size","28px");
      p.style("font-weight", "bold");

Emmet for sublime3

Emmet is a plugin for many popular text editors which greatly improves HTML & CSS workflow:
Emmet download

命令のショートカットキー(ctl + e)でコーディングの効率化します。

コマンド一覧
https://github.com/sergeche/emmet-sublime#readme

id
div#main -> ctl + e
span.blueItem -> ctl + e
ul>li -> ctl + e
div+div+div>p -> ctl + e
ul>li^div -> ctl + e

繰り返し
ul>li*3 -> ctl + e
ul>li.item$*3 -> ctl + e
table>tr*3>td*4 -> ctl + e
()
(ul>li*3)*2
a[title]
div{hello}
p>lorem
html>body>#main|e
#main>.sub>p*3|c
ul>li*3|s
html>body>#main>p*3|haml

-css
m, w, c-> ctl + e
-ctrl+w

chrome.contextMenus

右クリックで、twitter検索

{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "0.4",

	"description": "twitter search from context menu",

	"permissions": ["tabs", "http://*/*","https://*/*", "contextMenus"],

	"background": {
		"scripts": ["background.js"]
	}
}
chrome.contextMenus.create({
	"title":"「%s」をtwitterで検索",
	"type":"normal",
	"contexts":["selection"],
	"onclick": function(info){
		var url = 'https://twitter.com/search?q='+ encodeURIComponent(info.selectionText);
		chrome.tabs.create({
			url: url
		});
	}
});

ドキュメント
Chrome developer

Chrome Declare Permissions

ワイルドカードでパーミッションの権限を与えます。”permissions”: [“tabs”, “http://*/*”,”https://*/*”],

{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "0.1",

	"description": "背景色変更",

	"permissions": ["tabs", "http://*/*","https://*/*"],


	"browser_action":{
          "default_title": "Chrom Extension",      // optional; shown in tooltip
          "default_popup": "popup.html"
	}
}
function changeColor(color){
	chrome.tabs.executeScript(null, {
		"code": "document.body.style.backgroundColor='"+color+"'"
	});
}

document.getElementById('red').onclick = function(){
	changeColor('red');
}

document.getElementById('yellow').onclick = function(){
	changeColor('yellow');
}

chrome.browserAction

Chromeの拡張機能にパッケージ化されていない機能をmanifest.jsonで追加します。

{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "0.1",

	"description": "A plain text description",

	"browser_action":{
          "default_title": "Chrom Extension",      // optional; shown in tooltip
          "default_popup": "popup.html"
	}
}

Manifest File Format
Chrome developer

Arduino

void setup(){
  pinMode(LED_PIN, OUTPUT);
}

void loop(){
  digitalWrite(LED_PIN, HIGH);
  delay(500);
  digitalWrite(LED_PIN, LOW);
  delay(500);
}

ハードウェアの制御

#define LED_PIN 9

void setup(){
  pinMode(LED_PIN, OUTPUT);
}

void loop(){
  int i;
  for(i=0; i<256; i++){
  analogWrite(LED_PIN, i);
  delay(10);
  }
}

音声制御

#define LED_SPK 9

void setup(){
  pinMode(LED_PIN, OUTPUT);
}

void loop(){
  int i;
  for(i=0; i<256; i++){
  tone(SPK_PIN, i*10, 20);
  delay(10);
  }
}

タクトスイッチ

#define LED_PIN 13
#define BUTTON 2

void setup(){
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON, INPUT);
}

void loop(){
  if (digitalRead(BUTTON) == HIGH){
    digitalWrite(LED_PIN, HIGH);
  } else {
    digitalWrite(LED_PIN, LOW)
  }
}

Cdsセル

#define SENSOR 0

void setup(){
  pinMode(SENSOR, INPUT);
  Serial.begin(9600);
}

void loop(){
  int i;
  i = analogRead(SENSOR);
  Serial.print(i, DEC);
  Serial.print("\n");
  delay(1000);
}

画像作成アプリ

canvasで、ctx.moveTo(startX, startY);ctx.lineTo(x, y);ctx.stroke();で線を描画します。canvas.toDataURL().replace(‘image/png’,’application/octet-stream’)で、画像をダウンロードします。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Canvas</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <style>
    #mycanvas{
      border: 10px solid #999;
      cursor: crosshair;
    }
    .thumbnail{
      border: 2px solid #999;
      margin-right: 5px;
    }
    </style>
  </head>
  <body>
    <h1>Canvas</h1>
    <p>
      <select id="penColor">
        <option value="black">黒</option>
        <option value="red">赤</option>
        <option value="blue">青</option>
        <option value="white">白</option>
      </select>
      <select id="penWidth">
        <option value="1">細</option>
        <option value="3">中</option>
        <option value="5">太</option>
      </select>
        <input type="button" id="erase" value="消去">
        <input type="button" id="save" value="ギャラリーに追加">
    </p>
    <canvas id="mycanvas" width="400" height="200">
    Canvasの対応ブラウザを使用ください。</canvas>
    <div id="gallery"></div>
    <p>
    </p>
    <script>
      $(function(){
        var canvas = document.getElementById('mycanvas');
        if (!canvas || !canvas.getContext) return false;
        var ctx = canvas.getContext('2d');
        var startX,
            startY,
            x,
            y,
            borderWidth = 10,
            isDrawing = false;

        $('#mycanvas').mousedown(function(e){
            isDrawing = true;
            startX = e.pageX - $(this).offset().left - borderWidth;
            startY = e.pageY - $(this).offset().top - borderWidth;
        })
        .mousemove(function(e){
            if (!isDrawing) return;
            x = e.pageX - $(this).offset().left - borderWidth;
            y = e.pageY - $(this).offset().top - borderWidth;
            ctx.beginPath();
            ctx.moveTo(startX, startY);
            ctx.lineTo(x, y);
            ctx.stroke();
            startX = x;
            startY = y;
        })
        .mouseup(function() {
           isDrawing = false;
        })
        .mouseleave(function(){
           isDrawing = false;
        });

        $('#penColor').change(function(){
          ctx.strokeStyle = $(this).val();
        });
        $('#penWidth').change(function(){
          ctx.lineWidth = $(this).val();
        });
        $('#erase').click(function(){
            if(!confirm('本当に消去しますか?')) return;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        });
        $('#save').click(function(){
            var img = $('<img>').attr({
              width: 100,
              height: 50,
              src: canvas.toDataURL()
            });
            var link = $('<a>').attr({
              href: canvas.toDataURL().replace('image/png','application/octet-stream'),
              download: new Date().getTime() + '.png'
            });
            $('#gallery').append(link.append(img.addClass('thumbnail')));
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        });

      });
    </script>
  </body>
</html>

落下するアニメーション

window.onload = function(){
  draw();
}
function draw(){
  var canvas = document.getElementById('mycanvas');
  if (!canvas || !canvas.getContext)return false;
  var ctx = canvas.getContext('2d');

  ctx.fillStyle = "red"
  var y = 0;

  (function loop(){
    ctx.clearRect(0,0,canvas.width, canvas.height);
    if (y > canvas.height) y = -50;
    y++;
    ctx.fillRect(0,y,50,50);
    setTimeout(loop,10);
  })();
}

Canvasで遊ぼう

%e7%84%a1%e9%a1%8c

  ctx.shadowColor = "#ccc";
  ctx.shadowOffsetX = 5;
  ctx.shadowOffsetY = 5;
  ctx.shadowBlur = 5;

  ctx.globalAlpha = 0.5;

  ctx.fillRect(0, 0, 100, 100);

図形の変形

  ctx.scale(0.8,0.8);  
  ctx.rotate(30/180*Math.PI);
  ctx.translate(100, 10);

  ctx.fillRect(0, 0, 100, 100);

stroke

ctx.beginPath();
  ctx.moveTo(20, 20);
  ctx.lineTo(120,20);
  ctx.lineTo(120,120);
  ctx.stroke();

円形・曲線:round,butt,square

ctx.beginPath();
  ctx.arc(100,100,50,10/180*Math.PI,210/180*Math.PI);
  ctx.lineWidth = 15;
  ctx.lineCap = "round";
  ctx.stroke();

テキスト描画

  ctx.font = 'bold 20px Verdana';
  ctx.textAlign = 'left';
  ctx.fillStyle = 'red';

  ctx.fillText('Google', 20, 20, 40);
  ctx.strokeText('Google', 20, 120, 200);

画像表示

  var img = new Image();
  img.src = 'baby.jpg';
  img.onload = function(){
    ctx.drawImage(img, 10, 10);
  }

背景パターン

  var img = new Image();
  img.src = 'google.png';
  im.onload = function(){
    var patter = ctx.createPattern(img, 'repeat');
    ctx.fillStyle = pattern;
    ctx.fillRect(20, 20, 100, 100);
  }

設定の保存、復元

  ctx.fillStyle = "yellow";
  ctx.save();

  ctx.fillRect(0, 0, 50, 50);

  ctx.fillStyle= "blue";
  ctx.fillRect(100, 0, 50, 50);

  ctx.restore();
  ctx.fillRect(200, 0, 50, 50);
window.onload = function(){
  draw();
}
function draw(){
  var canvas = document.getElementById('mycanvas');
  if (!canvas || !canvas.getContext)return false;
  var ctx = canvas.getContext('2d');

  ctx.globalAlpha = 0.5;

  for (var i = 0; i < 100; i++){
    var x = Math.floor(Math.random() * 400);
    var y = Math.floor(Math.random() * 200);
    var r = Math.floor(Math.random() * 200);

    ctx.fillStyle = "rgb("+rgb()+","+rgb()+","+rgb()+")";
    ctx.beginPath();
    ctx.arc(x,y,r,0,2*Math.PI);
    ctx.stroke();
    ctx.fill();
  }

  function rgb(){
    return Math.floor(Math.random() * 255);
  }
}

Canvas

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Canvas</title>
  </head>
  <body>
    <h1>Canvas</h1>
    <canvas id="mycanvas" width="800" height="800">
    対応ブラウザを使用ください。</canvas>
    <p>
    </p>
  <script src="myscript.js"></script>
  </body>
</html>
window.onload = function(){
  draw();
}
function draw(){
  var canvas = document.getElementById('mycanvas');
  if (!canvas || !canvas.getContext)return false;
  var ctx = canvas.getContext('2d');

  //ctx.strokeRect(50, 10, 50, 150);
  ctx.fillRect(10, 10, 50, 50);
  ctx.clearRect(15, 15, 20, 20);
}

線の塗りやスタイル

  ctx.strokeStyle = "rgba(255, 0, 0, 0.5)";
  ctx.lineWidth = 15;
  ctx.lineJoin = "bevel";//"round";

  ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
  ctx.strokeRect(10, 10, 50, 50);
  ctx.fillRect(100, 10, 50, 50);

%e7%84%a1%e9%a1%8c

  var g = ctx.createLinearGradient(0, 0, 0, 100);
  g.addColorStop(0.0, "red");
  g.addColorStop(0.5, "yellow");
  g.addColorStop(1.0, "blue");
  ctx.fillStyle = g;

  ctx.fillRect(0, 0, 100, 100);

円形
var g = ctx.createRadialGradient(50, 50, 0, 50, 50, 80);