Skip to content

Instantly share code, notes, and snippets.

@snaka
Created May 9, 2009 10:17
Show Gist options
  • Save snaka/109212 to your computer and use it in GitHub Desktop.
Save snaka/109212 to your computer and use it in GitHub Desktop.
Canvasでテキストと角丸四角形を描画するサンプル
<html>
<head>
<title>Canvas tutorial</title>
<script type="text/javascript">
var ctx = null;
function draw(){
var canvas = document.getElementById('tutorial');
if (canvas.getContext){
ctx = canvas.getContext('2d');
drawText({ position: [50, 15], string: "hoge" });
roundedRectangle({
position:[25, 25, 100, 100],
lineWidth: 5,
radius: 20,
stroke: true,
strokeColor: "#00ff00",
fill: true,
fillColor: "#222222",
});
drawText({ position: [40, 60], string: "Q",
font: "40px monospace", color: "#ffffdd" });
drawText({ position: [40, 145], string: "かくまる" });
}
}
/*
* 角丸四角を描画する
*/
function roundedRectangle(param) {
var [x, y, width, height] = param.position;
var radius = param.radius;
// いろいろ変更する前に状態を保存
ctx.save();
// 線の太さとかを変更する前にsave()
ctx.lineWidth = param.lineWidth || 1;
// 縁の線の色はstrokeStyleで指定
ctx.strokeStyle = param.strokeColor || "black";
// 塗りつぶしの色はfillStyleで指定
ctx.fillStyle = param.fillColor || "black";
ctx.beginPath();
// 上辺の直線から描画を開始
// コーナーの曲線を考慮して円の半径分右よりから開始する
ctx.moveTo(x + radius, y);
// 上辺の終点、コーナーの曲線を考慮して円の半径分左よりになる
ctx.lineTo(x + width - radius, y);
// 右上コーナーの描画:
// - arcのx,y座標は円の中心
// - startAngle, endAngleはラジアンの単位,
// - Math.PIで180度,Math.PI*2でちょうど一周
// - 最後のパラメタは反時計回りに描画するかどうか、
// この場合時計回りに描画するのでfalse
ctx.arc(x + width - radius, y + radius, radius, Math.PI*1.5, 0, false);
// あと上記と同様、時計回りに描画を行っていく
ctx.lineTo(x + width, y + height - radius);
ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI*0.5, false);
ctx.lineTo(x + radius, y + height);
ctx.arc(x + radius, y + height - radius, radius, Math.PI*0.5, Math.PI, false);
ctx.lineTo(x, y + radius);
ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI*1.5, false);
ctx.closePath();
if (param.fill)
ctx.fill();
if (param.stroke)
ctx.stroke();
// 変更前の状態に戻す
ctx.restore();
}
/*
* テキストを出力する
*/
function drawText(param) {
var [x, y] = param.position;
var str = param.string;
var font = param.font || "16px Arial";
var color = param.color || "#000000";
ctx.save();
// mozTextStyle は deprecated FF3.5以降はfontプロパティを使う
ctx.mozTextStyle = font;
ctx.fillStyle = color;
// 文字の描画位置はtranslate()で行う
// ただし、translate()の後にはちゃんとrestore()しとかないと
// 座標がめちゃくちゃになってしまうのでsave()/restore()は要注意
ctx.translate(x, y);
// mozDrawText はdeprecated、FF3.5以降はfillText()/strokeText()を使う
ctx.mozDrawText(str);
ctx.restore();
}
</script>
<style type="text/css">
canvas { border: 1px solid black; }
</style>
</head>
<body onload="draw();">
<canvas id="tutorial" width="150" height="150"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment