Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - HTML5 edit text on the canvas

I'm trying to create something similar to http://www.listhings.com where you can edit the text within the canvas.

I've read the other post HTML5 Canvas Text Edit . But I don't want to edit the text outside of the canvas. I want to edit the text within the canvas.

I'd appreciate if anyone can point me in the right direction.
Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, Mohsen correctly points out that when you do context.fillText you are actually "painting a picture of letters" on the canvas. It's not like a word processor!

You can capture the key events on the window and then write the keystrokes out to your canvas.

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/7tXd4/

This example ONLY types lowercase a-z (no capitals, spaces, backspaces, etc)

You will probably want to make more enhancements like these:

Here's code just to get you started:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; padding:20px; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    ctx.font="18px Arial";

    var keyHistory="";

    window.addEventListener("keyup", keyUpHandler, true);

    function addletter(letter){
        keyHistory+=letter;
        ctx.clearRect(0,0,300,300);
        ctx.fillText(keyHistory,20,20);
    }

    function keyUpHandler(event){
        var letters="abcdefghijklmnopqrstuvwxyz";
        var key=event.keyCode;
        if(key>64 && key<91){
            var letter=letters.substring(key-64,key-65);
            addletter(letter);
        }
    }

}); // end $(function(){});
</script>

</head>

<body>
    <p>First click in the red canvas below</p><br/>
    <p>Then type any lowercase letters from a-z</p><br/>
    <canvas id="canvas" width=300 height=100></canvas>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...