Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...