How to insert an image in canvas and after that in

2019-06-03 23:27发布

I'm trying to insert an image in a canvas and after that I want to insert an input text in the same canvas, but I can't do it. How can I fix this problem?

Now, I want that the user insert a draggable text in the actual canvas. The people say that using Fabric.js is easy, but I can't get it working:

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条回答
乱世女痞
2楼-- · 2019-06-03 23:59

Using Scrawl.js:

(Disclaimer: I am the developer of this library)

<!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>

Working demo: over at jsFiddle

查看更多
劳资没心,怎么记你
3楼-- · 2019-06-04 00:06

Here is how to add user-specified text on an image and allow the text to be dragged

Enter image description here

This solution uses a canvas library called KineticJS and jQuery to simplify the task.

Here’s how it works:

  • Create the Kinetic Stage (this activates the HTML canvas)
  • Create a new image object in JavaScript (this loads your image into an object)
  • Create a new Kinetic Image object and put your new image in the Kinetic Image object
  • When the user types text in the input and hits the “Add” button…
  • Create a new Kinetic Label object using the user’s text
  • To make the new text label draggable, just set draggable:true when creating the object

Here’s the code that makes it all work…

Create the Kinetic Stage (this activates the HTML canvas)

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

Create a new image object in JavaScript (this loads your image into an object)

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";

Create a new Kinetic Image object and put your new image in the Kinetic Image object

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";

When the user types text in the input and hits the “Add” button…

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

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

    // Create your new kinetic text label here

});

Create a new Kinetic Label object using the user’s text

$("#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();
});

To make the new text label draggable, just set draggable:true when creating the object

// 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
});

You can download the Kinetic library and learn more with examples in HTML5 Canvas KineticJS Label Tutorial. You can download the jQuery library and learn more with examples here at the jQuery home page. jQuery is a great library for eliminating cross-browser inconsistencies.

Here is code and a Fiddle: 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>
查看更多
登录 后发表回答