やりたいこと
canvas上でクリックした際、クリック位置のマウス座標を取得し、その座標にtextareaを出現させるようなことを実現したいです。
やってみたこと
テキストボックスの内容を取得し、canvas上のクリックした位置に取得した内容を表示させるというものを作ってみました
ちなみに以下のコードになります。
html
<html> <head> <link rel="stylesheet" href="canvas.css" type="text/css"> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="canvas.js"></script> </head> <p id="tool"> <canvas id="axisCanvas" style="width: 700px; height: 800px; margin: 0 auto;position: absolute; left: 500px; top: 200px"></canvas> 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">
JavaScript
var canvas; // canvas要素(HTMLCanvasElement) var ctx; // 2Dコンテキスト(CanvasRenderingContext2D) var canvasW = 700; // canvas要素の横幅(px) var canvasH = 800; // canvas要素の縦幅(px) var mouseX; // 最後にクリックされた位置のx座標 var mouseY; // 最後にクリックされた位置のy座標 var text, size, color; window.onload = function() { // canvas要素を取得し、サイズ設定 canvas = document.getElementById('axisCanvas'); canvas.width = canvasW; canvas.height = canvasH; // 描画のために2Dコンテキスト取得 ctx = canvas.getContext('2d'); // クリックイベントの登録 canvas.onclick = function(e) { // 一度描画をクリア // クリック位置の座標計算(canvasの左上を基準。-2ずつしているのはborderの分) var rect = e.target.getBoundingClientRect(); mouseX = e.layerX; mouseY = e.layerY; // クリック位置を中心に円を描画 //ctx.beginPath(); //ctx.arc(mouseX/1.73, mouseY/1.95, 5, 0, Math.PI * 2, false); // ctx.fill(); text = $('#text').val(); size = $('#size').val(); color = $('#color').val(); console.log(size); console.log(mouseX + ","+mouseY); console.log("Math.floor(rect.left)"+Math.floor(rect.left)); console.log("rect.left"+rect.left); console.log("rect.top"+rect.top); console.log("e.clientX"+e.clientX); // 座標の表示テキストを描画 var maxWidth = 200; ctx.textAlign = 'right'; ctx.font = size+"px 'MS ゴシック'"; ctx.fillStyle = color; ctx.fillText(text, mouseX, mouseY); //setTF(this.form.txtField1,'visible',5,100); } };
ネット上で同じことをしようとしていると考えられる方のコードを利用してみましたがうまくいきませんでした。そのコードが以下のものになります。完全にお手上げ状態です。恐縮ですが詳しい方、何卒ご教授のほどお願い致します。
html
<html> <head> <meta charset="UTF-8" /> <title></title> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="canvas.js"></script> </head> <body> <canvas id="c" width="200" height="200"></canvas> </body> </html>
javascript
var canvas = document.getElementById("c"), textarea = null; canvas.addEventListener('onclick', function(e) { if(!textarea) { textarea = document.createElement('textarea'); textarea.className = 'info'; document.body.appendChild(textarea); } var x = e.clientX - canvas.offsetLeft, y = e.clientY - canvas.offsetTop; console.log("asasasasasasasasas"+x); textarea.value = "x: " + x + " y: " + y; textarea.style.top = e.clientY + 'px'; textarea.style.left = e.clientX + 'px'; }, false);
まだ回答がついていません
会員登録して回答してみよう