使用 Scrawl.js:
(免责声明:我是这个库的开发者)
<!DOCTYPE html>
<html>
<head>
<title>Scrawl.js</title>
<style>
body {margin: 1em;}
img {position: fixed; visibility: hidden;}
</style>
</head>
<body>
<ol>
<li>Display an image in a canvas</li>
<li>Add text to canvas</li>
<li>Drag text around canvas</li>
<li>Change text via an input box</li>
</ol>
<div>Change text by typing in this box: <input type="text" id="changetext" value="Hello world" /></div>
<img src="img/penguin02.jpg" id="penguin" class="demo903" />
<canvas id="mycanvas" width="400" height="400"></canvas>
<script src="js/scrawl.js"></script>
<script>
window.onload = function(){
//import the image and create a sprite to display it
scrawl.getImagesByClass('demo903');
scrawl.newPicture({
source: 'penguin',
width: 400,
height: 400,
});
//construct a sprite to display the text
//and a group for collision detection stuff
var texts = scrawl.newGroup({
name: 'texts',
});
var displayText = scrawl.newPhrase({
font: '24pt bold Arial, sans-serif',
textAlign: 'center',
textBaseline: 'middle',
startX: 200,
startY: 200,
fillStyle: 'yellow',
strokeStyle: 'black',
shadowColor: 'black',
shadowBlur: 8,
method: 'fillDraw',
text: 'Hello world',
group: 'texts',
});
//add event listeners to handle text drag-and-drop
var here, myText;
var getText = function(){
myText = texts.getSpriteAt(here);
if(myText){
myText.pickupSprite(here);
}
};
var dropText = function(){
if(myText){
myText.dropSprite();
myText = false;
}
};
scrawl.canvas.mycanvas.addEventListener('mousedown', getText);
scrawl.canvas.mycanvas.addEventListener('mouseup', dropText);
//add event listener for changing the text
var input = document.getElementById('changetext');
var updateText = function(e){
displayText.set({
text: input.value,
});
};
input.addEventListener('keyup', updateText);
//build an animation loop for updating the canvas
var myPad = scrawl.pad.mycanvas;
var animate = function(){
here = myPad.getMouse();
//drop the text if mouse moves out of the canvas area
if(!here.active && myText){
dropText();
}
scrawl.render()
requestAnimFrame(function(){
animate();
});
};
//start animation
animate();
};
</script>
</body>
</html>
工作演示:在 jsFiddle