[英]How to save Image from ctx.drawImage() to local storage
嗨,我想存儲我從網絡攝像頭捕獲的圖像。 我的計划是將圖片保存到本地存儲,然后在填寫所有表單字段后將其發布到后端。
這是我的方法(我使用 Vue Js)從網絡攝像頭拍攝照片
takePictureSelf() {
let ratio = (window.innerHeight < window.innerWidth) ? 16 / 9 : 9 / 16;
const picture = document.querySelector("canvas");
picture.width = (window.innerWidth < 1280) ? window.innerWidth : 1280;
picture.width = window.innerWidth / ratio;
const ctx = picture.getContext("2d");
ctx.imageSmoothingEnabled = true ;
ctx.imageSmoothingQuality = "high";
const gambar = document.querySelector("video");
ctx.drawImage(gambar,0,0,picture.width, picture.height)
}
我繪制了一些代碼來從畫布中獲取圖像數據。 您只需要將數據保存到localStorage
並將其發送到服務器。
document.getElementById("myImg").onload = function() { const img = document.getElementById("myImg"); const canvas = document.getElementById("myCanvas"); const pre = document.getElementById('myPre'); const ctx = canvas.getContext("2d"); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); const imageFileData = canvas.toDataURL('image/jpeg', 1); // for demo pre.innerHTML = imageFileData; };
canvas { display: none; } pre { white-space: pre-wrap; word-break: break-all; }
<img id="myImg" crossorigin="anonymous" src="https://loremflickr.com/50/50" /> <canvas id="myCanvas"></canvas> <pre id="myPre">image loading...</pre>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.