我们提供了使用此代码上传图片的选项:https://jsfiddle.net/bwdzha94/,它运行正常。
后来我们决定显示一些画布图像,所以我们使用了:https://jsfiddle.net/pmeb1uhm/1/
现在我合并这两个代码:jsfiddle.net/r22oka49/ [或下面的代码片段],我现在无法上传图片。
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
// var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
var oImg = img.set({left: 0, top: 0, angle: 00, width: canvas.getWidth(), height: canvas.getHeight()});
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
var img = new Image();
img.onload = function() {
//draw after loading
canvas = document.getElementById('case_canvas');
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
}
img.src = "http://i.stack.imgur.com/xgNw7.png";
//^^ this will start loading the image
/*.canvas-container {
background: url("http://i.stack.imgur.com/xgNw7.png") no-repeat fixed center;
}
*/
#canvas
{
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="canvas" width="450" height="450" ></canvas>
<div class="canvas-container" style="width: 300px; height: 500px; position: relative; -webkit-user-select: none;">
<canvas id="case_canvas" width="300" height="500" class="lower-canvas" style="position: absolute; width: 300px; height: 500px; left: 0px; top: 0px; -webkit-user-select: none;"></canvas>
<canvas class="upper-canvas " width="300" height="500" style="position: absolute; width: 300px; height: 500px; left: 0px; top: 0px; -webkit-user-select: none; cursor: default;"></canvas>
</div>
答案 0 :(得分:0)
您在var
中遗漏img.onload()
,覆盖了布料画布。
img.onload = function() {
//draw after loading
var canvas = document.getElementById('case_canvas');
//^^ create local variable instead of using the global one
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
}