LVS*_*AJE 0 html javascript svg canvas fabricjs
在我的页面上,我有一个按钮和一个具有以下属性的画布 -
<button onclick="openSVG()">Open</button>
<canvas></canvas>
Run Code Online (Sandbox Code Playgroud)
单击按钮时,该openSVG()功能应该
fabric.loadSVGFromString()方法填充画布现在单击“打开”按钮会打开一个文件选择窗口,但不会将对象绘制到画布中。这是我的 openSVG() 函数 -
function openSVG() {
// importing file
var input = $(document.createElement('input'));
input.attr("id", "mySVGFile")
input.attr("type", "file");
input.trigger('click');
//storing file contents in var using FileReader
var myInputFile = document.getElementById('mySVGFile');
var myFile = myInputFile.files[0];
var fr = new FileReader();
fr.onload = function(){
var canvasD = this.result;
//loading data from var to canvas
fabric.loadSVGFromString(canvasD, function(objects, options) {
var obj = fabric.util.groupSVGElements(objects, options);
canvas.add(obj).renderAll();
});
};
fr.readAsText(myFile); }
Run Code Online (Sandbox Code Playgroud)
我是 FileReader 的新手。控制台中没有错误,所以我什至不知道我哪里出错了。我的方法不起作用吗?有没有更好的方法来实现我想要的。
这是使用URL.createObjectURL()方法更容易和更好的方法......
var canvas = new fabric.Canvas('c');
function openSVG(e) {
var url = URL.createObjectURL(e.target.files[0]);
fabric.loadSVGFromURL(url, function(objects, options) {
objects.forEach(function(svg) {
svg.set({
top: 90,
left: 90,
originX: 'center',
originY: 'center'
});
svg.scaleToWidth(50);
svg.scaleToHeight(50);
canvas.add(svg).renderAll();
});
});
}Run Code Online (Sandbox Code Playgroud)
canvas{margin-top:5px;border:1px solid #ccc}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<input type="file" onchange="openSVG(event)">
<canvas id="c" width="180" height="180"></canvas>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4022 次 |
| 最近记录: |