Blazor server side - How to select camera and snap a picture - javascript

I have looked at all the examples I could find but cannot find an example that does both, select camera (front or rear) and snap an image.
How can I add to the example below the ability to select a different camera.
https://github.com/mdwaseelahmed/WebCamjsBlazorDemo
[wwwroot/webcamjs/Configuration.js]
function ready() {
if (document.readyState == 'complete') {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
try {
Webcam.attach('#camera');
} catch (e) {
alert(e);
}
}
}
function take_snapshot() {
// take snapshot and get image data
var data = null;
Webcam.snap(function (data_uri) {
data = data_uri;
});
return data;
}
[wwwroot/webcamjs/webcam.js]
I cannot add this file because it pushes over the body limit.
[_Host.cshtml]
#page "/"
#namespace WebcamjsDemo.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebcamjsDemo</title>
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<link href="WebcamjsDemo.styles.css" rel="stylesheet" />
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.server.js"></script>
<script type="text/javascript" src="~/webcamjs/webcam.min.js"></script>
<script src="~/webcamjs/Configuration.js"></script>
</body>
</html>
[Index.razor]
#page "/"
#inject IJSRuntime JSRuntime
<button #onclick="Capture">Capture</button>
<div class="col-md-2"></div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">Camera</div>
<div class="panel-body">
<div id="camera"></div>
<!-- A button for taking snaps -->
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">Captured Photo</div>
<div class="panel-body">
<div id="results">Your captured image will appear here...</div>
</div>
<br />
<br />
</div>
</div>
#foreach (var item in stringList)
{
<img src="#item" alt="Alternate Text" width="200px;" height="200px;" />
}
#code
{
List<string> stringList = new List<string>();
string aa = "";
public async void Capture()
{
stringList.Add(await JSRuntime.InvokeAsync<string>("take_snapshot"));
StateHasChanged();
}
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
JSRuntime.InvokeVoidAsync("ready", this);
}
}
}

I would suggest using the InputFile component. This one allows you to specify to use the camera, which will then trigger the native camera app where you can switch between both cameras.
<InputFile accept="image/png, image/gif, image/jpeg;capture=camera" OnChange="HandleFileSelected" />
capture=camera is the important part of this code.

Related

Display pokemon image [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I am trying to display the image from pokeapi but I get an error when I input the name. When I input the number I do get the pokemon image after clicking twice. But when I search for another pokemon I get a number of the previous pokemon. I would appreciate the help on the proper way to display the image. Thanks.
JS code is as follows:
document.querySelector("#search").addEventListener("click", getPokemon);
function getPokemon(e) {
const name = document.querySelector("#pokemonName").value;
fetch(`https://pokeapi.co/api/v2/pokemon/${name || id}`)
.then((res) => res.json())
.then((data) => {
console.log(data);
document.getElementById("data_id").innerHTML = data.id;
document.getElementById("data_name").innerHTML = data.name;
document.getElementById("data_type").innerHTML = data.types
.map((type) => type.type.name)
.join(", ");
document.getElementById("data_moves").innerHTML = data.moves
.map((move) => move.move.name)
.slice(0, 5)
.join(", ");
document.getElementById("search").addEventListener("click", getImage);
function getImage() {
const img = new Image();
img.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${name || id}.png`;
document.getElementById("image").appendChild(img);
}
})
.catch((err) => {
console.log("Error pokemon not found", err);
});
e.preventDefault();
}
HTML CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- CSS -->
<link rel="stylesheet" href="style.css" />
<!-- BOOTSTRAP -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous"
/>
<!-- Google fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Roboto+Mono&family=Unbounded&display=swap"
rel="stylesheet"
/>
<!-- cdnfonts -->
<link
href="https://fonts.cdnfonts.com/css/pokemon-solid"
rel="stylesheet"
/>
<title>Pokedex</title>
</head>
<body>
<div class="main-container">
<h1 class="heading">Pokemon</h1>
<form class="nameForm">
<input
type="text"
id="pokemonName"
name="pokemonName"
placeholder="Enter Pokemon Name"
/><br />
<button type="submit" class="sub-btn" id="search">Enter</button>
</form>
<div class="pokemonInfo container text-center">
<div id="image"></div>
<div class="row row-cols-2 gy-1">
<div class="pokemon-info-left dark-green col">Pokedex no.</div>
<div class="yellow col" id="data_id"></div>
<div class="w-100"></div>
<div class="pokemon-info-left light-green col">Name</div>
<div class="light col" id="data_name"></div>
<div class="w-100"></div>
<div class="pokemon-info-left dark-green col">Type</div>
<div class="yellow col" id="data_type"></div>
<div class="w-100"></div>
<div class="pokemon-info-left light-green col">Move</div>
<div class="light col data_moves" id="data_moves"></div>
</div>
</div>
</div>
<!-- Javascript -->
<script src="main.js"></script>
</body>
</html>
I tried a few ways cant seem to get it to work.
You can create a image tag inside of div#image and change its src attribute after you receive the response from the API. Here is how:
In you HTML code, add this:
<div id="image">
<img src="" alt="Pokemon Image" id="pokemon-image" />
</div>
In you JS code, remove these lines:
document.getElementById("search").addEventListener("click", getImage);
function getImage() {
const img = new Image();
img.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${name || id}.png`;
document.getElementById("image").appendChild(img);
}
and replace with these code:
const img_link = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${data.id}.png`
document.getElementById("pokemon-image").setAttribute("src", img_link);

Printing Modal Dialog Problem - output does not appear on the print preview screen

I am trying to print (PDF) a modal dialog on my Blazor Server Application. The modal dialog opens but unfortunately, the output does not appear on the print preview window. How can I print a modal dialog? Is there something I missed, I kindly request your help?
Here is the Radzen Modal Dialog:
Here is the empty print preview window:
Dialog razor:
#page "/dialogcard/{OrderID}"
#using IMS.CoreBusiness
#using IMS.UseCases.Interfaces.Order
#using IMS.UseCases.Orders
#inject IViewOrderByIdUseCase ViewOrderByIdUseCase
#inject Radzen.DialogService DialogService
#inject IJSRuntime JsRuntime
<div class="row">
<div class="col-lg-6 d-flex">
<RadzenCard Style="width: 100%; overflow: hidden;">
<h3 class="h5">Contact</h3>
<div class="d-flex flex-row">
#*<RadzenImage Path="#order?.DoneBy" Class="rounded-circle float-left mt-1 mr-3" Style="width: 90px; height: 90px;" />*#
<div>
<div>Employee</div>
<b>#order?.DoneBy</b>
<div class="mt-3">Company</div>
<b>#order?.Customer?.Name</b>
</div>
</div>
</RadzenCard>
</div>
<div class="col-lg-6 d-flex">
<RadzenCard Style="width: 100%; overflow: hidden;">
<h3 class="h5">Delivery Information</h3>
<div class="row">
<div class="col">
<div>Address</div>
<b>#(order?.OrderDetails?.Where(od => od.OrderId == OrderID).Select(x => x.ShippingNumber)), #(order?.OrderDetails?.Where(od => od.OrderId == OrderID).Select(x => x.TrackingNumber))</b>
<div class="mt-3">Vendor</div>
<b>#(order?.OrderDetails?.Where(od => od.OrderId == OrderID).Select(x => x.Vendor.Name))</b>
</div>
</div>
</RadzenCard>
</div>
</div>
<div class="row my-4">
<div class="col-md-12">
<RadzenCard>
<h3 class="h5">
Order #OrderID Details
<RadzenBadge BadgeStyle="BadgeStyle.Secondary" Text=#($"{String.Format(new System.Globalization.CultureInfo("en-US"), "{0:C}", order?.OrderDetails?.Where(od => od.OrderId == OrderID).Select(x => x.TotalBuyPrice))}") Class="float-right" />
</h3>
<RadzenDataGrid AllowFiltering="true" AllowPaging="true" AllowSorting="true" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive"
Data="#(orderDetails?.Where(o => o.Order?.Id == OrderID))" TItem="OrderDetail" ColumnWidth="200px" Class="mt-3">
<Columns>
<RadzenDataGridColumn TItem="OrderDetail" Property="Quantity" Title="Quantity" />
<RadzenDataGridColumn TItem="OrderDetail" Property="Order.OrderDate" Title="Order Date" />
<RadzenDataGridColumn TItem="OrderDetail" Property="Discount" Title="Discount" FormatString="{0:P}" />
</Columns>
</RadzenDataGrid>
</RadzenCard>
</div>
</div>
<div class="row hideWhenPrint">
<div class="col-md-12 text-right">
<RadzenButton Click="#((args) => DialogService.Close(false))" ButtonStyle="ButtonStyle.Secondary" Text="Close" Style="width: 120px" Class="mr-1" />
<RadzenButton Click="PrintDocument" Text="Print" Style="width: 120px" />
</div>
</div>
#code {
[Parameter] public int OrderID { get; set; }
Order? order;
IEnumerable<OrderDetail> orderDetails;
IList<Order?> SelectedOrders { get; set; }
IEnumerable<Order?> _orders = new List<Order?>();
protected override async Task OnInitializedAsync()
{
order = await ViewOrderByIdUseCase.ExecuteAsync(OrderID);
SelectedOrders = new List<Order?> { _orders.FirstOrDefault() };
}
private async Task PrintDocument(){
await JsRuntime.InvokeVoidAsync("Print");
}
}
Here is my print js:
function Print() {
$(".hideWhenPrint").hide();
window.print();
$(".hideWhenPrint").show();
}
Here is the _Layout.cshtml:
#using Microsoft.AspNetCore.Components.Web
#namespace IMS.WebApp.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<base href="~/"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css"/>
<link href="css/site.css" rel="stylesheet"/>
<link href="IMS.WebApp.styles.css" rel="stylesheet"/>
<link rel="stylesheet" href="_content/Radzen.Blazor/css/default.css">
<link href="css/sidebars.css" rel="stylesheet"/>
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered"/>
</head>
<body>
#RenderBody()
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.server.js"></script>
<script src="_content/Radzen.Blazor/Radzen.Blazor.js"></script>
<script src="~/jquery/jquery.min.js"></script>
<script src="~/bootstrap/js/bootstrap.min.js"></script>
<script src="~/js/myjs.js"></script>
<script>
window.downloadFileFromStream = async (fileName, contentStreamReference) => {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);
}
</script>
</body>
</html>
Edit1
I checked with Chrome developer tools and after I click the print button on the dialog, it gives this error on the console.
Unchecked runtime.lastError: The message port closed before a response was received.
Edit2
Adding <div id="printarea"> around the <div class="row"> of the dialog razor and using this CSS in the site.css solved my issue.
#media print {
body * {
visibility: hidden;
}
#printarea, #printarea * {
visibility: visible;
}
#printarea {
position: absolute;
left: 0;
top: 0;
}
}

Use ajax on client side when working with node

I have a very basic nodejs app that is displaying a html pages. This pages has two buttons linked with js function in a separated file. One of the function use ajax, the other not. The one using ajax is not working (not found I guess).
The external js file was working perfectly well under apache. Is there something specific to do to be able to use ajax on client side with node.js?
Here the node.js part:
var express = require ('express');
var app = express ();
app.use(express.static(__dirname + '/images'));
app.use(express.static(__dirname + '/CSS'));
app.use(express.static(__dirname + '/font'));
app.use(express.static(__dirname ));
app.use(express.static(__dirname +'/ChemAlive_JS'));
app.get('/', function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.sendFile('/home/laetitia/Project/ChemAlive_Interface_Node/test.html');
});
app.listen(8080);
The html part:
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="/Interface.css" type="text/css" rel="stylesheet" />
<link href="/ketcher.css" type="text/css" rel="stylesheet" />
<link href="/font-chemalive.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="/ddsmoothmenu.css" />
<link rel="stylesheet" type="text/css" href=/ddsmoothmenu-v.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/ui_bis.js"></script>
</head>
<body >
<div id="background">
<div id="LoginButton" class="deck login" >
<img class="LoginButtonUnpressed" alt="Login/Start" src="/ChemAlive_Start_Button.png">
<img class="LoginButtonPressed" alt="Login/Start" src="/ChemAlive_Start_Button_pressed.png">
<div class="popup" style="top: 0px; right: 80px;">
<p>Log-on or launch your calculations.</p>
</div>
</div>
<!-- Welcome Dialogue box -->
<div id="welcome_DB" class="dialogWindow fileDialog" >
<div class="h1">
<p>Welcome. Thank you for visiting our interface!</p>
</div>
<div class="iconDiv">
<img src="/Green_gears.png"/>
</div>
<div class="mainDiv">
<div class="desText">
<p>ChemAlive i</p>
</div>
</div>
<div class="navDiv">
<input type="submit" id="welcome_cancel" class="dialogButton" value="Cancel"/>
<label for="welcome_cancel" onclick="gototry();"><span class="label">Just Try It</span></label>
<input id="welcome_login" class="dialogButton" type="submit" value="Done"/>
<label for="welcome_login" style="right: 10px" onclick="gotologin();"><span class="label">Login</span></label>
<input id="welcome_register" class="dialogButton" type="submit" value="Done"/>
<label for="welcome_register" style="right: 20px" onclick="gotoregister();" ><span class="label">Registration</span></label>
</div>
</div>
<!-- Close welcome DB -->
</div>
</body>
</html>
And the external, client side, js:
$('LoginButton').observe('click', ui.onClick_login);
ui.onClick_login = function() {
window.alert("Hey There")
ui.showDialog('register_login');
}
function gototry() {
document.getElementById("welcome_DB").style.display = "none";
}
function gotologin() {
document.getElementById("welcome_DB").style.display = "none";
document.getElementById("login_v2").style.display = "inline-block";
}
function gotoregister() {
document.getElementById("welcome_DB").style.display = "none";
document.getElementById("register_DB").style.display = "inline-block";
}
Its $('LoginButton').observe('click', ui.onClick_login) call is not working.
Any ideas?
rename ui.onClick_login to a simple name like my_onclick_login
$('#LoginButton').observe('click', my_onclick_login);
my_onclick_login = function() {
window.alert("Hey There")
ui.showDialog('register_login');
}

Angularjs fails to dynamic change image src

Hello i'm building an application where i want to dynamically change the source of an image in order to force reload it . The problem is that in order of this i only get a broken image on the browser. Instead , if a run the function manually by a button it runs perfect .
HTML document
<!DOCTYPE html>
<html lang="en" ng-app='cameraApp'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Node JS Camera</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src='https://code.angularjs.org/1.4.4/angular-sanitize.min.js'></script>
<script src="cameraApp.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="jumbotron">
<h1>Welcome to NodeJS Camera v1</h1>
</div>
<div ng-controller="HomeController">
<div class="cameraControl col-md-5">
<p>Here is the camera control</p>
<button class="btn btn-default" ng-click="getSnapshot()">Snapshot</button>
<button class="btn btn-info" ng-click="intervalFunction()">Start Feed</button>
</div>
<div class="lifeFeed col-md-7">
<p>Here is the live feed</p>
<p><button class="btn btn-default" ng-click="readSnapshot()">Snapshot Read</button></p>
<img width='600' height='600' ng-src="{{snapshot}}" alt="SnapShot taken">
</div>
</div>
</div>
</body>
</html>
cameraApp.js
var cameraApp = angular.module('cameraApp',[]);
cameraApp.controller('HomeController', function($scope,$http,$timeout) {
function updateImage() {
var img = 'snapshots/camera.jpg'+ '?decache=' + Math.random();
console.log('Snapshot Loaded');
$scope.snapshot = img;
};
$scope.readSnapshot = updateImage;
$scope.getSnapshot = function() {
$http.get('/api/getSnapshot')
.then(function(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Snapshot captured');
$scope.readSnapshot();
}, function(response) {
console.log('Error in capturing...');
});
}
$scope.intervalFunction = function() {
$timeout(function() {
$scope.getSnapshot();
$scope.intervalFunction();
}, 2000);
};
// Kick off the interval
$scope.intervalFunction();
});
There are two solutions I've used for this in the past.
1) Use an ng-if/ng-show on your img tag. This will prevent the broken image from displaying.
<img ng-if='snapshot'>
2) Set a default image that will load and then be replaced once the other images load.
$scope.snapshot = 'snapshots/default.png';

Nokia HERE and Metro UI CSS 2.0 - shows white space instead of map

I'm creating a simple web application with Metro UI framework (http://metroui.org.ua/) where I would like to show a map.
I have decided to use Nokia HERE maps and its javascript API but even if I follow this example https://developer.here.com/javascript-apis/documentation/maps/topics/quick-start.html I'm getting just a white div with the HERE logo. The only browser where the map displays correctly is Chrome.
I figured out that problem must be somewhere in the compatibility between maps and metro-bootstrap.css because when I remove it, the maps show correctly. I use ASP.NET MVC with master page rendering.
Is there anyone who knows how to solve this issue?
Here is my HTML code
<!DOCTYPE html>
<html lang="cs">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="/js/jquery-2.1.0.min.js"></script>
<script src="/js/jquery-ui-1.10.4.min.js"></script>
<script src="http://js.api.here.com/se/2.5.4/jsl.js?with=all" type="text/javascript" charset="utf-8"></script>
<script src="/js/metro.min.js"></script>
<link href="/css/metro-bootstrap.css" rel="stylesheet" />
<link href="/css/metro-bootstrap-responsive.css" rel="stylesheet" />
<link href="/css/iconFont.min.css" rel="stylesheet" />
<link href="/css/customStyling.css" rel="stylesheet" />
<script src="/js/maps.js"></script>
</head>
<body class ="metro">
<div class="container">
<h1 class="fg-white"><span class="icon-cloudy on-left fg-white"></span>TEVI</h1>
<br />
<script src="/js/metro/metro-tile-transform.js"></script>
<script src="/js/user-interaction.js"></script>
<div id="tilesArea">
<div id="0" class="tile live double bg-lightBlue " data-role="live-tile" data-effect="slideUpDown" data-click="transform" data-period="3581" onclick="showDetails(this)">
<div class="tile-content text-left fg-white subheader text-left">
<div class="padding10"><span class="icon-thermometer on-left"></span>-10 °C</div>
</div>
<div class="tile-content text-left fg-white subheader text-left">
<div class="padding10"><span class="icon-rainy-2 on-left"></span>200 mm</div>
</div>
<div class="tile-status padding10">
<span class="name">Cidlo 1</span>
</div>
</div>
.
.
.
</div>
<hr />
<div id="detailsArea">
<p>
...
</p>
</div>
<hr />
</div>
<div id="mainMapArea"></div>
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Internet Explorer","requestId":"728fd54a207c4b32a11a57ed0a099b2b"}
</script>
<script type="text/javascript" src="http://localhost:49764/654ba5e681db49c6b825ad5f35203c7d/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
</html>
And here is javascript file maps.js which contain function to show the map:
function showStartupMap() {
nokia.Settings.set("app_id", "my app id");
nokia.Settings.set("app_code", "my app code");
nokia.Settings.set("serviceMode", "cit");
var map = new nokia.maps.map.Display(
document.getElementById("mainMapArea"), {
// Zoom level for the map
zoomLevel: 10,
// Map center coordinates
center: [52.51, 13.4]
}
);
}
$(document).ready(function () {
showStartupMap();
})
Any suggestions are welcome. Thank you

Categories

Resources