Skip to content

Instantly share code, notes, and snippets.

@rockos
Created January 14, 2017 07:06
Show Gist options
  • Save rockos/da6819e3d7345752b0c22abf844cdf2a to your computer and use it in GitHub Desktop.
Save rockos/da6819e3d7345752b0c22abf844cdf2a to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>KidsLab workshop</title>
<script src="main_move.js"></script>
<style>body{background:white;margin:0;padding:0;}</style>
</head>
<body>
<canvas id="world" style="display:block;margin:auto;"></canvas>
</body>
</html>
/* グローバル変数の宣言 */
var SCREEN_SIZE = 500; // キャンバスの幅
var SIDE_CELLS = 200; // 一辺のセルの数
var CELL_SIZE = SCREEN_SIZE / SIDE_CELLS; // セルの幅
var canvas; //= document.getElementById('world');
var context; //= canvas.getContext('2d');
var x, y, relX, relY, objX, objY;
var objWidth, objHeight;
var dragging = false;
var x, y, relX, relY, objX, objY;
var objWidth, objHeight;
window.onload = function() {
canvas = document.getElementById('world'); // canvas要素を取得
context = canvas.getContext('2d'); // コンテキスト
canvas.width = canvas.height = SCREEN_SIZE; // キャンバスのサイズを設定
objWidth = 50;
objHeight = 50;
objX = canvas.width / 2 - objWidth / 2;
objY = canvas.height / 2 - objHeight / 2;
drawShape();
canvas.addEventListener('mousedown', onDown, false);
canvas.addEventListener('mousemove', onMove, false);
canvas.addEventListener('mouseup', onUp, false);
}
function onDown(e) {
var offsetX = canvas.getBoundingClientRect().left;
var offsetY = canvas.getBoundingClientRect().top;
x = e.clientX - offsetX;
y = e.clientY - offsetY;
if (objX < x && (objX + objWidth) > x && objY < y && (objY + objHeight) > y) {
dragging = true;
relX = objX - x;
relY = objY - y;
}
}
function onMove(e) {
var offsetX = canvas.getBoundingClientRect().left;
var offsetY = canvas.getBoundingClientRect().top;
x = e.clientX - offsetX;
y = e.clientY - offsetY;
if (dragging) {
objX = x + relX;
objY = y + relY;
drawShape();
}
}
function onUp(e) {
dragging = false;
}
function drawShape() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(objX, objY, objWidth, objHeight);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment