pinpongゲーム

canvasを使って、x座標、y座標で、setTime関数で動かしています。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Pong Game</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="styles.css">
	<style>
		body {
			margin: 0;
			font-family: "Century Gothic";
			font-size: 16px;
		}
		#container {
			text-align: center;
			margin: 5px 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="280" height="280" id="mycanvas">
			Canvasに対応したブラウザを用意してください。
		</canvas>
		<div id="btn">START</div>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
	<script>
		$(function(){
			var ctx,
				myPaddle,
				myBall,
				mouseX,
				score,
				scoreLabel,
				isPlaying = false,
				timerId;

			var canvas = document.getElementById('mycanvas');
			if (!canvas|| !canvas.getContext) return false;
			ctx = canvas.getContext('2d');

			var Label = function(x, y){
				this.x = x;
				this.y = y;
				this.draw = function(text){
					ctx.font = 'bold 14px "Century Gothic"';
					ctx.fillStyle = '#00AAFF';
					ctx.textAlign = 'left';
					ctx.fillText(text, this.x, this.y);
				}
			}
			var Ball = function(x, y, vx, vy, r){
				this.x = x;
				this.y = y;
				this.vx = vx;
				this.vy = vy;
				this.r = r;
				this.draw = function(){
					ctx.beginPath();
					ctx.fillStyle = '#FF0088';
					ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI, true);
					ctx.fill();
				};
				this.move = function(){
					this.x += this.vx;
					this.y += this.vy;
					if (this.x + this.r > canvas.width || this.x - this.r < 0){
						this.vx *= -1;
					}
					if (this.y - this.r < 0){
						this.vy *= -1;
					}
					if (this.y + this.r > canvas.height){
						// alert("game over");
						isPlaying = false;
						$('#btn').text('REPLAY?').fadeIn();
					}
				};
				this.checkCollision= function(paddle){
					if ((this.y + this.r > paddle.y && this.y + this.r < paddle.y + paddle.h) &&
						(this.x > paddle.x - paddle.w / 2 && this.x < paddle.x + paddle.w /2)){
						this.vy *= -1;
						score++;
						if (score % 2 === 0){
							this.vx *= 1.3;
							paddle.w *= 0.9;
						}
					}
				}
			}

			var Paddle = function(w, h){
				this.w = w;
				this.h = h;
				this.x = canvas.width / 2;
				this.y = canvas.height - 30;
				this.draw = function(){
					ctx.fillStyle = '#00AAFF';
					ctx.fillRect(this.x - this.w / 2, this.y, this.w, this.h);
				};
				this.move = function(){
					this.x = mouseX - $('#mycanvas').offset().left;
				}
			};

			function rand(min, max){
				return Math.floor(Math.random() * (max - min + 1)) + min;
			}

			function init(){
				score = 0;
				isPlaying = true;
				myPaddle = new Paddle(100, 10);
				myBall = new Ball(rand(50, 250), rand(10, 80), rand(3, 8), rand(3, 8), 6);
				scoreLabel = new Label(10, 25);
				scoreLabel.draw('SCORE: ' + score);
			}
			

			function clearStage(){
				ctx.fillStyle = '#AAEDFF';
				ctx.fillRect(0, 0, canvas.width, canvas.height);
			}

			function update(){
				clearStage();
				scoreLabel.draw('SCORE: ' + score);
				myPaddle.draw();
				myPaddle.move();
				myBall.draw();
				myBall.move();
				myBall.checkCollision(myPaddle);
				timerId =setTimeout(function(){
					update();
				}, 30);
				if(!isPlaying) clearTimeout(timerId);
			}

			$('#btn').click(function(){
				$(this).fadeOut();
				init();
				update();
			});


			$('body').mousemove(function(e){
				mouseX = e.pageX;
			});
		});
	</script>
</body>
</html>

jQuery plug-in 作成

jQueryのプラグイン作成に、fn.extend()を使います。
jQuery.fn.extend():Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods.
https://api.jquery.com/jquery.fn.extend/

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>jQuery plugin</title>
  </head>
  <body>
      <p><img src="image01.jpg"></p>
      <p><img src="image02.jpg"></p>
      <p><img src="image03.jpg"></p>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
      <script src="jquery.showsize.js"></script>
      <script>
        $(function(){
          $('img').showsize({
            size: 22,
            opacity: 0.9
          });
        });
      </script>
  </body>
</html>
;(function($){
	$.fn.showsize = function(options){
		var elements = this;

		elements.each(function(){

			var opts = $.extend({}, $.fn.showsize.defaults, options, $(this).data());
			$(this).click(function(){
            var msg = $(this).width() + ' x ' + $(this).height();
            $(this).wrap('<div style="position:relative;"></div>');
            var div = $('<div>')
                    .text(msg)
                    .css('position', 'absolute')
                    .css('top', '0')
                    .css('padding', '2px')
                    .css('background', getRandomColor())
                    .css('font-size', opts.size +'px')
                    .css('color','white')
                    .css('opacity',opts.opacity);
            $(this).after(div);
          });

		});

		return this;
	};

	function getRandomColor(){
		var colors = ['red', 'pink', 'orange', 'green', 'blue'];
		return colors[Math.floor(Math.random()* colors.length)];
	}

	$.fn.showsize.defaults = {
		size: 10,
		opacity: 0.8
	};
})(jQuery);

画像作成アプリ

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>

日付カウントダウン

setTimeoutは、一定時間後に特定の処理をおこなう(繰り返さずに一度だけ)処理です。setTimeout(function(){
getResult();},200);で、0.2秒ごとに処理を繰り返します。new Date().getTime();から、Date.now()を引いた秒数で表示しています。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css?family=Bilbo" rel="stylesheet">
    <title>Web font</title>
    <style>
    body {
      font-family: 'Bilbo', cursive;
      background: #000;
      text-align: center;
      font-size:36px;
      color:red;
    }
    h1 {
      color: #fff;
      font-size: 128px;
      margin:0;
    }
    #remainingDays, #remainingTime {
      font-size: 64px;
    }
    </style>
  </head>
  <body>
    <h1>Q</h1>
    <p>
      <span id="remainingDays"></span>days <span id="remainingTime"></span> to go
    </p>
  <script>
  function getResult(){
    var target = new Date(2020, 04, 01, 10, 0, 0).getTime();
    var now = Date.now();
    var diff = (target - now) /1000;
    var d = Math.floor(diff / 60 / 60/ 24);
    diff = diff - 60 * 60 * 24 * d;
    var h = Math.floor(diff / 60 / 60);
    diff = diff - 60 * 60 * h;
    var m = Math.floor(diff / 60);
    diff = diff - 60 * m;
    var s = Math.floor(diff);

    document.getElementById('remainingDays').innerHTML = d;
    document.getElementById('remainingTime').innerHTML = padZero(h)  + ':' + padZero(m) + ':' + padZero(s);
    setTimeout(function(){
    getResult();
  },200);
  }
  getResult();

  function padZero(n){
    return (n < 10) ? '0'+n : n;
  }

  </script>
  </body>
</html>

二次元バーコード生成

jQuery doc
.attr()
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>二次元バーコード</title>
    <style>
    body {

    }
    </style>
  </head>
  <body>
    <h1>二次元バーコード</h1>
    <p>
      <input type="text" id="msg">
      <input type="button" value="変換" id="button">
    </p>
    <div id="barCode"></div>
  <script>
    $(function(){
      $('#button').click(function(){
          var msg = encodeURIComponent($('#msg').val());
          var img = $('<img>').attr('src', 'http://chart.apis.google.com/chart?cht=qr&chs=150x150&choe=Shift_JIS&chl='+msg);
          $('#barCode').html(img);
      });
    });
  </script>
  </body>
</html>

jQuery LocalStorage メモ帳

localStorage.getItemでデータを取得、localStorage.setItemでローカル保存、localStorage.removeItemでデータを削除します。保存した場合は、ブラウザを更新しても、データが残っております。 $(‘#memo’).bind(‘keyup’, function() のbind ‘keyup’は、キーボード入力時に、キーボードが上がった場合に呼び出されます。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>メモ帳</title>
    <style>
    body {

    }
    </style>
  </head>
  <body>
    <h1>メモ帳</h1>
    <textarea id="memo" rows="10" cols="40" name="40"></textarea>
    <p><input type="button" id="clear" value="消去"></p>
    <script>
    $(function(){
      if (localStorage.getItem('memo')){
        $('#memo').val(localStorage.getItem('memo'));
      }

      $('#clear').click(function(){
        $('#memo').val('');
        localStorage.removeItem('memo');

      });

      $('#memo').bind('keyup', function(){
        localStorage.setItem('memo', $('#memo').val());
      });

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

local storageのドキュメントはjqueryの公式サイトなどを参照ください。
https://plugins.jquery.com/tag/localstorage/

jQuery マウスの座標軸の取得


マウスの座標軸を$(‘#container’).mousemove(function(e){ console.log(e.clientX, e.clientY); で取得し、中心からの距離に合わせてオブジェクトの形状を変える処理です。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <title>パララックスサイト</title>
    <style>
    body {
      margin: 0;
      padding: 0;
    }
    #container {
      width: 600px;
      height: 280px;
      background: #eee;
    }
    .box {
      position: fixed;
      opacity: 0.6;
      left: 300px;
    }
    #box1 {
      width: 40px;
      height: 40px;
      top: 140px;
      background: red;
    }
    #box2 {
      width: 50px;
      height: 50px;
      top: 155px;
      background: blue;
    }
    #box3 {
      width: 60px;
      height: 60px;
      top: 165px;
      background: yellow;
    }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div id="container">
    <div id="box1" class="box"></div>
    <div id="box2" class="box"></div>
    <div id="box3" class="box"></div>
    </div>
    <script>
    $(function(){
      $('#container').mousemove(function(e){
          console.log(e.clientX, e.clientY);
          var cx = $(this).width() / 2;
          var cy = $(this).height() / 2;
          var dx = e.clientX - cx;
          var dy = e.clientY - cy;
          $('#box1').css('left', cx + dx * 1.1);   
          $('#box2').css('left', cx + dx * 1.3); 
          $('#box3').css('left', cx + dx * 1.5);
          $('#box1').css('top', cy + dy * 1.0);   
          $('#box2').css('top', cy + dy * 1.1); 
          $('#box3').css('top', cy + dy * 1.2);        
      });
    });
    </script>
  </body>
</html>

jQuery パララックス2

cssのbackground-positionを$(window).scroll(function(){ var dy = $(this).scrollTop(); で操作します。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <title>パララックスサイト</title>
    <style>
    body {
      margin: 0;
      padding: 0;
      height: 3000px;
    }
    .box {
      padding: 0;
      margin:0;
      height: 340px;
    }
    #bg1 { background: url('p1.jpg') no-repeat; }
    #bg2 { background: url('p2.jpg') no-repeat; }
    #bg3 { background: url('p3.jpg') no-repeat; }
    #msg {
      font-size: 48px;
      font-weight: bold;
      font-family: Verdana, Arial, sans-serif;
      color: orange;
      opacity: 0;
      position: fixed;
    }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div id="bg1" class="box"></div>
    <div id="bg2" class="box"></div>
    <div id="bg3" class="box"></div>
    <div id="msg" class="box">The End</div>
    <script>
    $(function(){
      $(window).scroll(function(){
        var dy = $(this).scrollTop();
        console.log(dy);

        $('#bg1').css('background-position', '0 '+dy+'px');

        if (dy > 340) {
          $('#bg2').css('background-position', (dy-340)+'px '+(dy-340)+'px');
        } else {
          $('#bg2').css('background-position', '0 0');
        }

        if (dy > 680) {
          $('#bg3').css('background-position', '0 '+(dy-680)*2+'px');
        } else {
          $('#bg3').css('background-position', '0 0');
        }
        if (dy > 680) {
          $('#msg').css('opacity', (dy-680)/340);
          $('#msg').css('top', 200);
          var dx = (dy -680) > 400 ? 400: (dy-680);
          $('#msg').css('left', dx);
        } else {
          $('#msg').css('opacity', 0);
        }

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

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

jQuery パララックス1

scrollTop();でスクロール位置を取得し、それに合わせてオブジェクトを変形します。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <title>パララックスサイト</title>
    <style>
    body {
      margin: 0;
      padding: 0;
      height: 3000px;
    }
    .box {
      height: 40px;
      width: 40px;
      position: fixed;
      top: 10px;
    }
    #box1 { left: 10px; background: red; }
    #box2 { left: 60px; background: blue; }
    #box3 { left: 110px; background: green; }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <div id="box1" class="box"></div>
    <div id="box2" class="box"></div>
    <div id="box3" class="box"></div>
    <script>
    $(function(){
      var pos1 = $('#box1').offset();
      var pos2 = $('#box2').offset();
      var pos3 = $('#box3').offset();
      $(window).scroll(function(){
        var dy = $(this).scrollTop();
        console.log(dy);

        $('#box1').css('top', pos1.top +dy / 2);
        $('#box1').css('left', pos1.left +dy / 8);
        $('#box2').css('top', pos2.top +dy / 5);
        $('#box2').css('left', pos2.left +dy / 2);
        $('#box3').css('top', pos3.top +dy / 7);
        $('#box3').css('left', pos3.left +dy / 4);
      });
    });
    </script>
  </body>
</html>

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

jQuery thumbnail スライドショー

タイマー処理を使って、自動再生のスライドショーを作成します。
timer = setTimeout(function(){
autoPlay();

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQueryスライドショー</title>
    <style>
    body {
      margin: 10px auto;
      text-align: center;
    }
     .thumbnail{
          width: 125px;
          height:83px;
          opacity: 0.5;
          cursor:pointer;
     }
     .current {
      opacity: 1;
     }
     .thumbnail + .thumbnail {
      margin-left: 4px;
     }
    </style>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
      <div id="thumbnails"></div>
      <div id="main"></div>
      <div id="nav">
          <button id="prev">&laquo; 前へ</button>
          <button id="next">次へ&raquo; </button>
          <button id="play">再生</button>
          <button id="stop">停止</button>
      </div>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script>
      $(function(){
          var files = [
            '01.jpg',
            '02.jpg',
            '03.jpg',
            '04.jpg'
          ];
            var img;
            var timer;
            var currentNum = 0;
            var nowPlaying = false;
            for (var i = 0; i < files.length; i++){
              img = $('<img>').attr('src', files[i]).addClass('thumbnail');
              $('#thumbnails').append(img);
            }
            $('#main').append(
                $('<img>').attr('src', files[0])
              );
            $('.thumbnail:first').addClass('current');
            $('.thumbnail').click(function(){
              $('#main img').attr('src', $(this).attr('src'));
              currentNum = $(this).index();
              $(this).addClass('current').siblings().removeClass('current');
            });
            $('#prev').click(function(){
              currentNum--;
              if (currentNum < 0){
                currentNum = files.length -1;
              }
              $('#main img').attr('src', files&#91;currentNum&#93;);
              $('.thumbnail').removeClass('current');
              $('.thumbnail').eq(currentNum).addClass('current');
            });
            $('#next').click(function(){
              currentNum++;
              if (currentNum > files.length - 1){
                currentNum = 0;
              }
              $('#main img').attr('src', files[currentNum]);
              $('.thumbnail').removeClass('current');
              $('.thumbnail').eq(currentNum).addClass('current');
            });
            function autoPlay(){
              $('#next').click();
              timer = setTimeout(function(){
                  autoPlay();
              }, 1000);
            }
            $('#play').click(function(){
                  if (nowPlaying) return;
                  nowPlaying = true;
                autoPlay();
            });
            $('#stop').click(function(){
                    clearTimeout(timer);
                    nowPlaying = false;
            });
      });
      </script>
  </body>
</html>

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