canvas でハートマークを書いてみる
androidの図形描画についての質問です。 CANVASにdrawRectでハート型を描画したいと思っています。 色々検索してみましたが、ハート型のサンプル等がなく困っています。 ハートを描画するコードやサンプルが載っているURL等教えていただけないでしょうか。 よろしくお願いします。canvas で、ハートマークを書いてみる。
式は、StackOverflow に落ちてたのを使った (wolframalpha.com へのリンク)。
ソースは、こんな感じ。
<canvas id="canvas-h"></canvas> <style type='text/css'> #canvas-h { border: 5px inset pink; background: #fff; } </style> <script type='text/javascript'> $(function() { /* http://stackoverflow.com/questions/14325779/draw-heart-shape-android-canvas?rq=1 */ function heart_function(t) { var r = (Math.sin(t)*Math.sqrt(Math.abs(Math.cos(t))))/(Math.sin(t) + 7.0/5.0) -2*Math.sin(t) + 2.0; return r; } CoordSupport = function() { this.init = function(cw, ch, x_min, x_max, y_min, y_max) { this.width_ = cw; this.height_ = ch; this.x_min_ = x_min; this.x_max_ = x_max; this.y_min_ = y_min; this.y_max_ = y_max; this.dx_ = (x_max - x_min) / cw; this.dy_ = (y_max - y_min) / ch; }; this.pixel = function(x, y) { var px = (x - this.x_min_) / (this.x_max_ - this.x_min_) * this.width_; var py = (this.y_max_ - y) / (this.y_max_ - this.y_min_) * this.height_; return {"x": px, "y": py}; }; }; function draw_heart() { var canvas = document.getElementById('canvas-h'); if (!canvas || !canvas.getContext) { alert("not support CANVAS !"); return false; } var cs = new CoordSupport(); cs.init(300, 350, -3, 3, -5, 2); canvas.width = cs.width_; canvas.height = cs.height_; var ctx = canvas.getContext('2d'); ctx.strokeStyle = "pink"; ctx.beginPath(); var p = cs.pixel(0, 0); ctx.moveTo(p.x, p.y); var PI2 = Math.PI * 2.0; var dt = PI2 / 360; for (t = 0 ; t <= PI2 ; t += dt) { var r = heart_function(t); var x = r * Math.cos(t); var y = r * Math.sin(t); p = cs.pixel(x, y); ctx.lineTo(p.x, p.y); } ctx.stroke(); ctx.fillStyle = "pink"; ctx.fill(); ctx.closePath(); } draw_heart(); }); </script>
他にも、こんな式がある。
- http://d.hatena.ne.jp/Zellij/20111205/p1
- http://homepage3.nifty.com/kuebiko/science/freestdy/MthHeart.htm
- http://www16.ocn.ne.jp/~akiko-y/heart/index_heart.html
それと、この回答にあったコードなんだけど、けっこう、あちこちで見つかる。
MDC (Mozilla Developer Center) にある、このサンプルが拡散しているのかな?
って、ここまで書いて、ようやく気が付いた。
質問にある CANVAS って、android.graphics.Canvas のことか。
java のコードが欲しかったのね (´・ω・`)