HTML5のCanvas要素へクリックでテキストを描画する : JavaScript

Pocket

Canvas要素のマウスクリックされた位置へinput要素の文字を挿入する。


<p id="tool">
Text: <input id="text" name="text" type="text" value="Example"> |
Size: <input id="size" name="size" type="text" size="3" value="14"> |
Color: <input id="color" name="color" type="text" size="7" value="#000">
</p>

<canvas id="canvas" name="canvas" width="200" height="200"></canvas>

&lt;

p id="clear"><button>Clear</button>

<h1>tool {</h1>

<pre><code>margin: 20px 20px 10px;
</code></pre>

}

<h1>canvas {</h1>

<pre><code>margin: 10px 20px;
border: 2px dotted #DDD;
</code></pre>

}

<h1>clear {</h1>

<pre><code>margin: 10px 20px;
</code></pre>

}
/**
 * set Canvas
 */
var canvas, cxt;
(function() {
    canvas = $('#canvas');
    cxt = canvas.get(0).getContext('2d');
}());
/**
 * draw text
 */
canvas.click(function(e) {
    var pos;
    // to do error check<br />
    // draw text
    pos = getMousePosition(e, canvas.get(0));
    drawText(pos);
});

function drawText(pos) {
    var text, size, color;

<pre><code>text = $('#text').val();
size = $('#size').val();
color = $('#color').val();

text = (text === '') ? 'Example' : text;
color = (color === '') ? '#000' : color;
size = (size === '') ? '14px' : parseInt(size, 10) + 'px';

cxt.clearRect(0, 0, canvas.width, canvas.height);

cxt.font = size + ' "sans-serif"';
cxt.fillStyle = color;
cxt.fillText(text, pos.x, pos.y);
</code></pre>

}

// get mouse click position

function getMousePosition(mouseEvent, targetCanvas) {
    var x, y;
    if (mouseEvent.pageX != undefined &amp;&amp; mouseEvent.pageY != undefined) {
        x = mouseEvent.pageX;
        y = mouseEvent.pageY;
    } else {
        x = mouseEvent.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        y = mouseEvent.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

<pre><code>return {
    x: x - targetCanvas.offsetLeft,
    y: y - targetCanvas.offsetTop
};
</code></pre>

}

// clear canvas text
$('#clear button').click(function() {
    cxt.clearRect(0, 0, canvas.width(), canvas.height());
})

» HTML 5 Canvas – A Simple Paint Program (Touch and Mouse) – CodeProject

» jsFiddle

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。