这是我第一次使用HTML canvas。我得到了一个可以正常工作的相机,该相机返回的图像为base64字符串。我正在尝试将此字符串传递给处理图像大小调整的新函数(当前的大小并不重要,因为我只是在测试调整大小)。
现在,我从generateThumbnail函数中得到一张空白图像。在下面,我附加了应用程序中输出的图像以及控制台输出中的图像。 对于第一个附加的图像,您将看到2张照片。左侧的照片是可以正常工作的原始照片(由于覆盖了我的网络摄像头,因此全黑)。尝试调整大小时,右边的照片为空白输出。
generateThumbnail(imageData) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0, 300, 300);
}
img.src = imageData;
let dataUrl = canvas.toDataURL("image/png");
console.log(imageData);
console.log(dataUrl);
return dataUrl;
}
答案 0 :(得分:0)
尽管您的代码无法在嵌入式小提琴上运行,但我认为您的问题是因为在执行方法后立即返回dataUrl
时,图像尚未加载。
dataUrl
应该在img.onload
方法内部返回,也许类似的东西会起作用?
**编辑**
确保同时设置画布的宽度和高度。
const generateThumbnail = (imageData) => {
let canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 300;
document.querySelector(".canvas").appendChild(canvas);
let ctx = canvas.getContext("2d");
let img = new Image();
img.onload = () => {
ctx.drawImage(img, 0 , 0, 300, 300);
console.log(imageData);
console.log(dataUrl);
return dataUrl;
}
img.src = imageData;
let dataUrl = canvas.toDataURL("image/png");
document.querySelector(".image").appendChild(img);
}
window.onload = () => {
generateThumbnail(window.image_base64);
}
.canvas, .image {
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 300px;
color: white;
}
.image { border: solid 1px white; }
.canvas {
left: 310px;
top: 0;
width: 300px;
height: 300px;
}
body {
background: purple;
}
<div class="image"></div>
<div class="canvas"></div>
<script>
window.image_base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAMAAABOo35HAAAFU2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJ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