Javascript 从画布获取后图像不显示
我正在使用Vue,需要在上传前预览文件,如果文件是图像,则减小其大小(使用画布)并显示,否则只需使用画布显示文件的扩展名,因此我做了如下操作:Javascript 从画布获取后图像不显示,javascript,html,canvas,html5-canvas,Javascript,Html,Canvas,Html5 Canvas,我正在使用Vue,需要在上传前预览文件,如果文件是图像,则减小其大小(使用画布)并显示,否则只需使用画布显示文件的扩展名,因此我做了如下操作: // I have used this function in the html like <img src={{ imagePreviewURL(File) }} /> imagePreviewURL(File) { // <-- get the uploaded file const canvas = document.crea
// I have used this function in the html like <img src={{ imagePreviewURL(File) }} />
imagePreviewURL(File) { // <-- get the uploaded file
const canvas = document.createElement('canvas')!; // <-- create canvas
const ctx = canvas.getContext('2d')!;
canvas.width = 100;
canvas.height = 100;
if (File.type.includes('image')) { // <-- if file is image
const image = new Image(); // <-- create new image
image.onload = () => {
ctx.drawImage(image, 100, 100); // <-- draw image to canvas
};
image.src = URL.createObjectURL(File); // <-- set source of image
} else {
ctx.font = '30px Arial';
ctx.textAlign = 'center';
ctx.fillText(`.${File.name.split('.').pop()!}`, 50, 55); // <-- just display extension
}
return ctx.canvas.toDataURL(); // <-- convert canvas to image
}
//我在html中使用过这个函数,比如
imagePreviewURL(文件){//image.onload
是异步的,在返回ctx.canvas.toDataURL()之前它不会运行
因此,在函数返回之前,您的图像不会被绘制到画布上。您能给出解决方案吗?如何异步等待它?安装文件发送事件并像-:此方法在Chrome和Webkit as window.webkitURL.createObjectURL()中作为前缀。您应该测试URL是否存在,然后使用适当的对象:(window.URL?URL:webkitURL).createObjectURL(evt.data);@LDS已完成此操作。image.onload
是异步的,在返回ctx.canvas.toDataURL()之前不会运行
因此,在函数返回之前,您的图像不会被绘制到画布上。您能给出解决方案吗?如何异步等待它?安装文件发送事件并像-:此方法在Chrome和Webkit as window.webkitURL.createObjectURL()中作为前缀。您应该测试URL是否存在,然后使用适当的对象:(window.URL?URL:webkitURL).createObjectURL(evt.data);@LDS已经这样做了。