How to Upload and load image in Konvajs canvas?
Asked Answered
Q

1

7

I have used konva js plugin for canvas representation. I have gone through the document, but can't get any help to upload the image using konvajs.

Is it so that I need to do custom code? Does konva js support image upload from folder and save to canvas elements?

How upload/store external image is managed?

Qualls answered 14/10, 2019 at 11:2 Comment(2)
See modified answer below.Warmth
Hi - if my answer was correct please could you mark it as the correct answer by clicking the tick. Marking the correct or most helpful answer helps other people judge its relevance and awards points to the answerer. Thanks.Warmth
W
11

Your question is really about how to let the user select an image and get that displayed in an img element in the browser. Once the img element is loaded you can use that to draw in to a Konva.Image element.

I adapted the code from this question which shows how to load a local image into an HTML img element - then modified it to load the image into a Konva image object on a canvas.

I realise this is plain JS, but you should be able to find Vue examples of loading the local image on the Internet - just use the onload event to handle the Konvajs steps.

// Create the stage and a layer to draw on.
var stage = new Konva.Stage({
  container: 'canvas-container',
  width: 650,
  height: 300
});

var layer = new Konva.Layer();
stage.add(layer);
stage.draw();

// listen for the file input change event and load the image.
$("#file_input").change(function(e){

    var URL = window.webkitURL || window.URL;
    var url = URL.createObjectURL(e.target.files[0]);
    var img = new Image();
    img.src = url;


    img.onload = function() {

      var img_width = img.width;
      var img_height = img.height;

      // calculate dimensions to get max 300px
      var max = 300;
      var ratio = (img_width > img_height ? (img_width / max) : (img_height / max))

      // now load the Konva image
      var theImg = new Konva.Image({
        image: img,
        x: 50,
        y: 30,
        width: img_width/ratio,
        height: img_height/ratio,
        draggable: true,
        rotation: 20
      });

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


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script        src="https://cdnjs.cloudflare.com/ajax/libs/konva/3.2.5/konva.min.js"></script>
<div>Render a local image without upload</div>
<div>
  <input type="file" id="file_input">
</div>
<div id="canvas-container" style='display: inline-block; border: 1px solid #ccc;  background-color: #ccc; overflow: auto;'></div>
Warmth answered 14/10, 2019 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.