Skip to content

Instantly share code, notes, and snippets.

@314maro
Last active August 29, 2015 14:18
Show Gist options
  • Save 314maro/b36ee3e5b6853e6b767a to your computer and use it in GitHub Desktop.
Save 314maro/b36ee3e5b6853e6b767a to your computer and use it in GitHub Desktop.
jsの練習
<!DOCTYPE html>
<html>
<head lang="ja">
<meta charset="UTF-8" />
<title>こんにちは世界</title>
<script>
'use strict';
var canvas, ctx;
window.onload = function () {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
window.onmousemove = showCoordinate;
canvasSize();
canvasSetup();
canvas.onmousedown = drawStart;
canvas.onmouseout = mouseout;
window.onmouseup = mouseout;
canvas.onmousemove = drawLine;
};
function canvasSetup () {
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
mouseout();
}
function mouseout () { canvas.isOver = false; };
function drawStart (ev) {
// http://cpplover.blogspot.jp/2009/06/dom-level-3.html
var rect = event.target.getBoundingClientRect();
var x = ev.clientX - rect.left;
var y = ev.clientY - rect.top;
canvas.isOver = true;
ctx.beginPath(); ctx.moveTo(x,y);
}
function drawLine (ev) {
var rect = event.target.getBoundingClientRect();
var x = ev.clientX - rect.left;
var y = ev.clientY - rect.top;
if (canvas.isOver) {
ctx.lineTo(x,y); ctx.stroke();
}
}
function showCoordinate (ev) {
var x = ev.clientX;
var y = ev.clientY;
document.getElementById('mouseX').value = x;
document.getElementById('mouseY').value = y;
};
function draw1 () {
ctx.fillRect(0,0,50,50);
ctx.beginPath();
ctx.moveTo(0,60); ctx.lineTo(10,70); ctx.lineTo(50,60);
ctx.stroke();
}
function clearButton () {
ctx.clearRect(0,0,canvas.width,canvas.height);
}
function canvasSize () {
canvas.width = document.getElementById('canvasWidth' ).value;
canvas.height = document.getElementById('canvasHeight').value;
canvasSetup();
}
function selectColor (ev) {
ctx.strokeStyle = ev.target.value;
ctx.fillStyle = ev.target.value;
}
function lineWidth (ev) {
ctx.lineWidth = + ev.target.value;
}
</script>
<style>
canvas {
border: solid black;
}
</style>
</head>
<body>
<p>
<canvas id="canvas">Canvasがサポートされていない。</canvas>
</p>
<p>
<button onclick="draw1()">draw</button>
<button onclick="clearButton()">clear</button>
<select onchange="selectColor(event)">
<option value="black">black</option>
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select>
<input type="text" onchange="lineWidth(event)" value="1"></input>
</p>
<p>
<input type="text" id="canvasWidth" placeholder="width" value="800"></input>
<input type="text" id="canvasHeight" placeholder="height" value="500"></input>
<button onclick="canvasSize()">ok</button>
</p>
<p>
<input type="text" id="mouseX" disabled="true"></input>
<input type="text" id="mouseY" readonly="true"></input>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment