使用选择选项或使用上传将图像添加到画布并绘制它

时间:2014-09-25 17:37:00

标签: javascript html5 image canvas

你能帮我解决这个问题吗?我正在寻找如何通过上传添加图像或使用选择按钮添加现有图像,然后在图像中绘制并最后将其保存到DB中,就像图像的琵琶一样(例如images / canvas / draw1.jpg或。 PNG)

我遵循这两个教程......但我不知道如何完成

select-diferent-image-for-canvas-background

dynamically-add-image-to-canvas

1 个答案:

答案 0 :(得分:0)

此示例允许您的用户将图片从桌面拖到背景画布上:



var canvas = document.getElementById("bk");
var bkctx = canvas.getContext("2d");

// dropzone event handlers
var dropzone;
dropzone = document.getElementById("dropzone");
dropzone.addEventListener("dragenter", dragenter, false);
dropzone.addEventListener("dragover", dragover, false);
dropzone.addEventListener("drop", drop, false);

//
function dragenter(e) {
    e.stopPropagation();
    e.preventDefault();
  }
  //

function dragover(e) {
  e.stopPropagation();
  e.preventDefault();
}

//
function drop(e) {
  e.stopPropagation();
  e.preventDefault();

  var dt = e.dataTransfer;
  var files = dt.files;

  handleFiles(files);
}

//
function handleFiles(files) {

    for (var i = 0; i < files.length; i++) {

      // get the next file that the user selected
      var file = files[i];
      var imageType = /image.*/;

      // don't try to process non-images
      if (!file.type.match(imageType)) {
        continue;
      }

      // a seed img element for the FileReader
      var img = document.createElement("img");
      img.classList.add("obj");
      img.file = file;

      // get an image file from the user
      // this uses drag/drop, but you could substitute file-browsing
      var reader = new FileReader();
      reader.onload = (function(aImg) {
        return function(e) {
          aImg.onload = function() {
              // draw the aImg onto the canvas
              bkctx.clearRect(0, 0, canvas.width, canvas.height);
              bkctx.drawImage(aImg, 0, 0);
            }
            // e.target.result is a dataURL for the image
          aImg.src = e.target.result;
        };
      })(img);
      reader.readAsDataURL(file);

    } // end for

  } // end handleFiles
&#13;
body {
  background-color: ivory;
}
#dropzone {
  border: 1px solid blue;
  position: relative;
  width: 300px;
  height: 300px;
}
canvas {
  border: 1px solid red;
  position: absolute;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Drag an image from desktop to blue dropzone.</h4>
<div id="dropzone" width=300 height=300>
  <canvas id="bk" width=300 height=300></canvas>
  <canvas id="canvas" width=300 height=300></canvas>
</div>
&#13;
&#13;
&#13;

相关问题