開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Safari(Web browser)
Head First HTML5 Programming (Elisabeth Robson (著)、Eric Freeman (著)、O'Reilly Media)の Chapter 7.(Bringing Out Your Inner Artist: The Canvas)、CODE MAGNETS(No. 5103) を取り組んでみる。
CODE MAGNETS(No. 5103)
コード(Emacs)
HTML5
<canvas id="canvas0" width="600" height="600" style="border:solid brown; border-radius:10px"></canvas>
<br>
<p>
<label for="backgroundColor0">Select background color:</label>
<select id="backgroundColor0">
<option value="white" selected="selected">White</option>
<option value="black">Black</option>
</select>
</p>
<p>
<label for="foregroundColor0">Select foreground color:</label>
<select id="foregroundColor0">
<option value="black" selected="selected">Black</option>
<option value="white">White</option>
</select>
</p>
<button id="draw0">draw</button>
<button id="clear0">clear</button>
<script src="sample4.js"></script>
JavaScript
let btn0 = document.querySelector('#draw0'),
btn1 = document.querySelector('#clear0');
let canvas = document.querySelector('#canvas0'),
context = canvas.getContext('2d'),
width = canvas.width,
height = canvas.height;
let fillBackgroundColor = (canvas, context) => {
let selectObj = document.querySelector('#backgroundColor0'),
index = selectObj.selectedIndex,
bgColor = selectObj.options[index].value;
context.fillStyle = bgColor;
context.fillRect(0, 0, width, height);
};
let drawSquare = (canvas, context) => {
let w = Math.floor(Math.random() * width),
h = Math.floor(Math.random() * height),
x = Math.floor(Math.random() * width - w / 2),
y = Math.floor(Math.random() * height - h / 2),
r = Math.floor(Math.random() * 256),
g = Math.floor(Math.random() * 256),
b = Math.floor(Math.random() * 256);
context.fillStyle = `rgb(${r}, ${g}, ${b})`;
context.fillRect(x, y, w, h);
};
let drawText = (canvas, context) => {
let selectObj = document.querySelector('#foregroundColor0'),
index = selectObj.selectedIndex,
fgColor = selectObj[index].value;
context.fillStyle = fgColor;
context.font = 'bold 1em sans-serif';
context.textAlign = 'left';
context.fillText('I saw this tweet', 20, 40);
context.font = 'bold 1em sans-serif';
context.textAlign = 'right';
context.fillText('and all I got was this lousy t-shirt!', width - 20, height - 40);
};
let draw = () => {
fillBackgroundColor(canvas, context);
drawSquare(canvas, context);
drawText(canvas, context);
};
btn0.onclick = () => {
draw();
};
btn1.onclick = () => {
context.clearRect(0, 0, width, width);
};
draw();
0 コメント:
コメントを投稿