我有一个文件输入,其中所选文件必须转换为图像url,以便我可以将其添加到画布中。
我已经发现SVG是一个例外,所以我需要在将其转换为图像URL之前将其转换为Blob。将其转换为Blob似乎工作正常,但将其转换为url会返回意外结果。
相关代码:
function initiate() {
var canvas = $("#canvas").get(0);
var context = canvas.getContext("2d");
var img = new Image();
var imageSrcUrl;
img.onload = function() {
URL.revokeObjectURL(imageSrcUrl), {once: true}
context.drawImage(
img,
0,
0,
img.width,
img.height,
0,
0
);
}
var extension = $("#logo").get(0).files[0].name.split('.').pop().toLowerCase();
if(extension == 'svg') {
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result);
var blob = new Blob([reader.result.toString()], {type: 'image/svg+xml'});
console.log(blob);
imageSrcUrl = URL.createObjectURL(blob);
console.log(imageSrcUrl);
img.src = imageSrcUrl;
};
reader.readAsText($("#logo").get(0).files[0]);
} else {
img.src = URL.createObjectURL(
$("#logo").get(0).files[0]
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form id="form">
Select file here
<input type="file" id="logo">
</form>
<br><br>
Canvas goes here
<canvas width="400" height="200" id="canvas"></canvas>
<br><br>
<button onclick="initiate();">Get svg into canvas</button>
控制台日志:
我是遗漏了什么还是做错了什么?我从https://dev.to/benjaminblack/using-a-string-of-svg-as-an-image-source-8mo那里得到了方法
谢谢!
您已经指定了dx
和dy
值…
这些值可用于在画布上渲染之前选择像素图像的区域。
这些参数不适用于svg
图像。
将DrawImage参数更改为:
context.drawImage(
img,
0,
0,
img.width,
img.height
);
function initiate() {
var canvas = $("#canvas").get(0);
var context = canvas.getContext("2d");
var img = new Image();
var imageSrcUrl;
img.onload = function() {
URL.revokeObjectURL(imageSrcUrl), {once: true}
context.drawImage(
img,
0,
0,
img.width,
img.height
);
}
var extension = $("#logo").get(0).files[0].name.split('.').pop().toLowerCase();
if(extension == 'svg') {
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result);
var blob = new Blob([reader.result.toString()], {type: 'image/svg+xml'});
console.log(blob);
imageSrcUrl = URL.createObjectURL(blob);
console.log(imageSrcUrl);
img.src = imageSrcUrl;
};
reader.readAsText($("#logo").get(0).files[0]);
} else {
img.src = URL.createObjectURL(
$("#logo").get(0).files[0]
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form id="form">
Select file here
<input type="file" id="logo">
</form>
<br><br>
Canvas goes here
<canvas width="400" height="200" id="canvas"></canvas>
<br><br>
<button onclick="initiate();">Get svg into canvas</button>