如何在画布中插入图像,然后在此画布中插入文本?

时间:2013-08-31 11:25:11

标签: html5 canvas fabricjs

我正在尝试在画布中插入图像,之后我想在同一画布中插入输入文本,但我不能这样做。我该如何解决这个问题?

现在,我希望用户在实际画布中插入可拖动文本。人们说使用Fabric.js很容易,但我无法使用它:

canvas = document.getElementById("canvasThumbResult");
var context = canvas.getContext("2d");
var img = document.getElementById("target");
context.drawImage(img, getX, getY, getWidth, getHeight, 0, 0, 238.11023622,332.598425197);

2 个答案:

答案 0 :(得分:4)

以下是如何在图片上添加用户指定的文字并允许拖动文字

Enter image description here

此解决方案使用名为KineticJS和jQuery的画布库来简化任务。

以下是它的工作原理:

  • 创建Kinetic Stage(这会激活HTML画布)
  • JavaScript中创建一个新的图像对象(这会将图像加载到对象中)
  • 创建一个新的Kinetic Image对象并将新图像放入Kinetic Image对象
  • 当用户在输入中键入文本并点击“添加”按钮...
  • 使用用户的文字
  • 创建一个新的Kinetic Label对象
  • 要使新文本标签可拖动,只需在创建对象时设置draggable:true

这是让它全部工作的代码......

创建Kinetic Stage(这会激活HTML画布)

var stage = new Kinetic.Stage({
    container: 'container',
    width: 300,
    height: 300
});
var layer = new Kinetic.Layer();
stage.add(layer);

在JavaScript中创建新的图像对象(这会将图片加载到对象中)

var image = new Image();
image.onload = function(){

        // Your image is fully loaded, so…

        // Create your kinetic image object here

    layer.add(image1);
    layer.draw();
}
image.src="koolaidman.png";

创建一个新的动态图像对象并将新图像放入动态图像对象

var image = new Image();
image.onload = function(){
    var image1 = new Kinetic.Image({
        x: 0,
        y: 0,
        width: 300,
        height: 300,
        image: image,
    });
    layer.add(image1);
    layer.draw();
}
image.src = "koolaidman.png";

当用户在输入中输入文字并点击“添加”按钮时...

<input id="newtext" type="text" value="Hello!">
<button id="addbutton">Add this text</button>

$("#addbutton").click(function(){

    // Create your new kinetic text label here

});

使用用户的文字

创建新的Kinetic Label对象
$("#addbutton").click(function(){

      // Simple label
      var label = new Kinetic.Label({
          x: 20,
          y: 20,
          draggable:true
      });

      label.add(new Kinetic.Tag({
          fill: 'green'
      }));

      label.add(new Kinetic.Text({
          text: $("#newtext").val(),
          fontFamily: 'Verdana',
          fontSize: 18,
          padding: 10,
          fill: 'white'
      }));

      layer.add(label);
      layer.draw();
});

要使新文本标签可拖动,只需在创建对象时设置draggable:true

// Snipped from the kinetic label creation above

var label = new Kinetic.Label({
    x: 20,
    y: 20,

    // Set draggable:true to make the kinetic label draggable
    draggable:true
});

您可以下载动态库,并通过 HTML5 Canvas KineticJS Label Tutorial 中的示例了解详情。您可以在jQuery home page下载jQuery库并通过示例了解更多信息。 jQuery是一个很好的库,可以消除跨浏览器的不一致性。

这是代码和小提琴:http://jsfiddle.net/m1erickson/pQYz9/

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Prototype</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
        <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.6.0.min.js"></script>
        <style>
            #container{
              border:solid 1px #ccc;
              margin-top: 10px;
              width:300px;
              height:300px;
            }
        </style>
        <script>
            $(function(){
                $("#addbutton").click(function(){
                      // Simple label
                      var label = new Kinetic.Label({
                          x: 20,
                          y: 20,
                          draggable:true
                      });

                      label.add(new Kinetic.Tag({
                          fill: 'green'
                      }));

                      label.add(new Kinetic.Text({
                          text: $("#newtext").val(),
                          fontFamily: 'Verdana',
                          fontSize: 18,
                          padding: 10,
                          fill: 'white'
                      }));

                      layer.add(label);
                      layer.draw();
                });
            }); // End $(function(){});
        </script>
    </head>

    <body>
        <input id="newtext" type="text" value="Hello!">
        <button id="addbutton">Add this text</button>
        <div id="container"></div>
    </body>
</html>

答案 1 :(得分:1)

使用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>

工作演示:over at jsFiddle