问题描述
我想拖动文本,它位于Canvas,我找到一个教程如何拖动矩形,但我不能实现它的文本,这是以下代码移动矩形,可以有人帮助我实现it on Text?
I want to Drag Text which is located on the Canvas , I found a tutorial How to Drag a Rectange but i could not implement it on text , This is the Following code for moving the rectangle , can some one help me to implement it on Text ?
<!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
此外,当我在HEAD标记中添加此代码时,它不起作用。为什么会这样?
And also when i add this Code in the HEAD tag it does not work. Why is it so ?
推荐答案
基本示例
提供一个(保留rect函数,添加新文本函数,绘制文本的边框)
Prettied up one (kept rect function, added new text function, draws the bounding box for the text)http://jsfiddle.net/h3BCq/2/
我绝对被骗了。我使用px的字体大小更容易抓取其宽度。你可以使用em的或点,虽然你只需要做一个转换像素,以获得一个估计的宽度。我基本上只是删除了rect,并添加了filltext,并修改检查以检查文本宽度。
I definitely cheated. I used px for the font size to easier grab its width. You could use em's, or points though you would just need to do a conversion to pixels to get an estimated width. I Basically just removed rect, and added filltext, and modified the check to check for the text width.
这篇关于HTML5画布 - 在画布上拖动文本问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!