2017年4月14日金曜日

開発環境

Head First HTML5 Programming (Elisabeth Robson (著)、Eric Freeman (著)、O'Reilly Media)の Chapter 7.(Bringing Out Your Inner Artist: The Canvas)、SHARPEN YOUR PENCIL(No. 4854) を取り組んでみる。

SHARPEN YOUR PENCIL(No. 4854)

コード(Emacs)

HTML5


<canvas id="canvas0" width="600" height="600" style="border:solid brown; border-radius:10px"></canvas>
<br>
<select id="backgroundColor0">
  <option value="white" selected="selected">White</option>
  <option value="black">Black</option>
</select>

<button id="draw0">draw</button>
<button id="clear0">clear</button>
<script src="sample2.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 draw = () => {
    fillBackgroundColor(canvas, context);
    drawSquare(canvas, context);
};

btn0.onclick = () => {
    draw();
};

btn1.onclick = () => {
    context.clearRect(0, 0, width, width);
};

draw();

0 コメント:

コメントを投稿

Comments on Google+: