How to upload image into HTML5 canvas

前端 未结 3 949
滥情空心
滥情空心 2020-11-27 10:41

I am currently using http://paperjs.org to create an HTML5 canvas drawing app. I want to let users upload images into the canvas. I know I need to make a login and signup bu

相关标签:
3条回答
  • 2020-11-27 11:19

    One doesn't need a FileReader*, it is better to use the URL.createObjectURL method, which will create a symlink directly to the File on disk. This will incur less memory usage, and will have the added benefit to have only one async event to wait for (the one of the img.onload).

    document.getElementById('inp').onchange = function(e) {
      var img = new Image();
      img.onload = draw;
      img.onerror = failed;
      img.src = URL.createObjectURL(this.files[0]);
    };
    function draw() {
      var canvas = document.getElementById('canvas');
      canvas.width = this.width;
      canvas.height = this.height;
      var ctx = canvas.getContext('2d');
      ctx.drawImage(this, 0,0);
    }
    function failed() {
      console.error("The provided file couldn't be loaded as an Image media");
    }
    <input type="file" id="inp">
    <canvas id="canvas"></canvas>

    *IIRC only a few versions of Chrome did support FileReader while not yet supporting URL.createObejctURL, so if you target these very versions, you might need FileReader..

    0 讨论(0)
  • 2020-11-27 11:30
    <script>
    window.onload = function() {
    var canvas=document.getElementById(“drawing”); // grabs the canvas element
    var context=canvas.getContext(“2d”); // returns the 2d context object
    var img=new Image() //creates a variable for a new image
    
    img.src= “images/vft.jpg” // specifies the location of the image
    context.drawImage(img,20,20); // draws the image at the specified x and y location
    }
    </script>
    

    Check Demo

    0 讨论(0)
  • 2020-11-27 11:37

    I assume you mean, to load an image into the canvas and not uploading the image from the canvas.

    It'd probably be a good idea to read through all the canvas articles they have over here https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

    But basically what you want to do is create an image in javascript, and set the image.src = to whatever the file location is. In the case of loading images from the user on their end, you're going to want to use the File System API.

    Threw together a brief example here: http://jsfiddle.net/influenztial/qy7h5/

    function handleImage(e){
        var reader = new FileReader();
        reader.onload = function(event){
            var img = new Image();
            img.onload = function(){
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img,0,0);
            }
            img.src = event.target.result;
        }
        reader.readAsDataURL(e.target.files[0]);     
    }
    
    0 讨论(0)
提交回复
热议问题