gpt4 book ai didi

javascript - Blob 图像无法使用 JavaScript 进入 Canvas

转载 作者:行者123 更新时间:2023-12-02 17:29:58 24 4
gpt4 key购买 nike

我能够将图像上传到浏览器并将其转换为 BLOB。之后,我尝试将其绘制到 Canvas 中,但它没有被识别。我有一种感觉,我错过了一些小东西,但我看不到它。任何帮助都会很棒!

var resize_img  = 
function(){

var file = document.getElementById("add_img").files;

// add in file type checker

// Create img element to PREVIEW
var img = document.createElement("img");
img.src = window.URL.createObjectURL(file[0]);


// Draw image to CANVAS
var canvas_e = document.getElementById("canvas_img");
var ctx = canvas_e.getContext("2d");
ctx.drawImage(img, 0, 0);

//Resize Image
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;

if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas_e.width = width;
canvas_e.height = height;
ctx.drawImage(img, 0, 0, width, height);


//Push Data
var dataurl = canvas_e.toDataURL("image/png");
console.log(dataurl);

}

HTML

<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<!-- CSS -->
<link href="css/main.css" rel="stylesheet" type="text/css" >
</head>
<body>
<input type="file" id="add_img" onchange="resize_img()">
<canvas id="canvas_img"></canvas>
<!-- JS -->
<script src="js/main.js" type="text/javascript"></script>
</body>
</html>

最佳答案

将canvas代码放入img.onload=function () {.... }

关于javascript - Blob 图像无法使用 JavaScript 进入 Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23158832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com