function init_event() {
    var canvas = $('c');
        canvas.addEventListener('click', function(e) {
            get_value(e, canvas);
        }, false);
}

function init_canvas() {
    var img = new Image();
        img.src = "./image/tori.jpg";

    var canvas = $('c');
    var ctx = canvas.getContext('2d');

        canvas.width = img.width;
        canvas.height = img.height;

        ctx.drawImage(img, 0, 0, img.width, img.height);

    init_event();
}


function get_value(evt, canvas) {
    var x = evt.offsetX;
    var y = evt.offsetY;

    var gctx = canvas.getContext('opera-2dgame');
    var rgb = gctx.getPixel(x, y);

    var r_16 = rgb.substr(1, 2);
    var g_16 = rgb.substr(3, 2);
    var b_16 = rgb.substr(5, 2);

    set_value(x, y, r_16, g_16, b_16);
}

function set_value(x, y, r, g, b) {
    var rx = eval('0x' + r);
    var gx = eval('0x' + g);
    var bx = eval('0x' + b);

    $('x').value = x;
    $('y').value = y;
    $('r').value = rx;
    $('g').value = gx;
    $('b').value = bx;

    $('color').style.background = '#' + r + g + b;
}

function $(el) {
    return $[el] || ($[el] = document.getElementById(el));
}

window.addEventListener('load', init_canvas, false);

