2011-02-16 154 views
4

我想拖動位於畫布上的文本,我找到了一個教程如何拖動Rectange但我無法在文本上實現它,這是移動矩形的以下代碼,有人可以幫我在Text上實現嗎?HTML5畫布 - 在畫布上拖動文本問題

<!doctype html> 
<html> 
<head> 
<meta charset="UTF-8" /> 
<title>Canvas Drag and Drop Test</title> 
</head> 
<body> 
<section> 

<div> 
<canvas id="canvas" width="400" height="300"> 
This text is displayed if your browser does not support HTML5 Canvas. 
</canvas> 
</div> 

<script type="text/javascript"> 

var canvas; 
var ctx; 
var x = 75; 
var y = 50; 
var dx = 5; 
var dy = 3; 
var WIDTH = 400; 
var HEIGHT = 300; 
var dragok = false; 

function rect(x,y,w,h) { 
ctx.beginPath(); 
ctx.rect(x,y,w,h); 
ctx.closePath(); 
ctx.fill(); 
} 

function clear() { 
ctx.clearRect(0, 0, WIDTH, HEIGHT); 
} 

function init() { 
canvas = document.getElementById("canvas"); 
ctx = canvas.getContext("2d"); 
return setInterval(draw, 10); 
} 

function draw() { 
clear(); 
ctx.fillStyle = "#FAF7F8"; 
rect(0,0,WIDTH,HEIGHT); 
ctx.fillStyle = "#444444"; 
rect(x - 15, y - 15, 30, 30); 
} 

function myMove(e){ 
if (dragok){ 
    x = e.pageX - canvas.offsetLeft; 
    y = e.pageY - canvas.offsetTop; 
} 
} 

function myDown(e){ 
if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 + 
canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop && 
e.pageY > y -15 + canvas.offsetTop){ 
    x = e.pageX - canvas.offsetLeft; 
    y = e.pageY - canvas.offsetTop; 
    dragok = true; 
    canvas.onmousemove = myMove; 
} 
} 

function myUp(){ 
dragok = false; 
canvas.onmousemove = null; 
} 

init(); 
canvas.onmousedown = myDown; 
canvas.onmouseup = myUp; 

</script> 

</section> 
</body> 
</html> 

Test

而且還當我添加此代碼頭標記這是行不通的。爲什麼這樣?

回答

8

基本例如 http://jsfiddle.net/h3BCq/1/

美化了一番一個(保持RECT功能,增加了新的文本功能,繪製邊框文本) http://jsfiddle.net/h3BCq/2/

我肯定被騙了。我使用字體大小的px來更容易地抓住它的寬度。您可以使用em或點,但您只需對像素進行轉換即可獲得估計的寬度。我基本上只是刪除了矩形,並添加了filltext,並修改了檢查以檢查文本寬度。

+0

爲什麼當我將所有腳本代碼放入HEAD標記時,此代碼不起作用? – Yahoo 2011-02-16 17:44:03