JavaScript - Unable to run 'getImageData' method on 'CanvasRenderingContext2D': Provided value is not a 'long' type

My setup involves a video element and a canvas element as seen below:

<video id="video" width="640" height="480"></video>
<canvas id="canvas" width="640" height="480"></canvas>

The goal is to decode a PDF417 barcode from the webcam feed.

First, here's the code snippet to request permission to use the webcam:

if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
        video.srcObject = stream;
        video.play();
    });
}

Next, I attempt to capture the barcode using the camera and decode it:

canvas_context.drawImage(video, 0, 0, 640, 480);

try {

    var source = new ZXing.BitmapLuminanceSource(canvas_context, video);

    var binarizer = new ZXing.Common.HybridBinarizer(source);
    var bitmap = new ZXing.BinaryBitmap(binarizer);

    console.log(JSON.stringify(ZXing.PDF417.PDF417Reader.decode(bitmap, null, false), null, 4));

} catch (err) {

    console.log(err);

}

However, an error occurs with the message:

Failed to execute 'getImageData' on 'CanvasRenderingContext2D': Value is not of type 'long'.

This error originates from this line of code:

var source = new ZXing.BitmapLuminanceSource(canvas_context, video);

Which points to the following method:

ZXing.BitmapLuminanceSource = function (bitmap, w, h) {
  
  // The rest of the function remains the same

};

I'm seeking help in understanding what went wrong. Why am I encountering this error and how can it be resolved?

Answer №1

Within this function's parameters, an HTMLImageElement is accepted as the w parameter. This element provides access to its properties like naturalWidth and naturalHeight. On the other hand, an HTMLVideoElement does not possess these properties, but utilizes videoWidth and videoHeight.

To simplify utilizing this complex function, consider passing an ImageData instead:

const data = canvas_context.getImageData(0, 0, 640, 480);
source = new ZXing.BitmapLuminanceSource(data)

Answer №2

Your code structure is quite perplexing. When calling the BitmapLuminanceSource function, you pass in two parameters (a canvas context and a video source), whereas the function itself expects arguments of (bitmap, w, h) - leading to potential confusion for readers who may interpret it as a bitmap with width and height parameters.

Additionally, there is an abrupt introduction of a variable named 'canvas' which causes further confusion since typically a canvas and its context are paired together. If a canvas object was truly needed, it should have been passed along with its context.

The assignment of the input parameter 'w' to this newfound 'canvas' variable adds to the bewilderment, especially considering that 'w' was previously being repeatedly set as a width parameter elsewhere in the code.

If we assume 'w' represents the canvas connected to the earlier mentioned canvas context, we encounter the crux of the issue: both width and height values supplied to getImageData are either undefined or zero, as the canvas element lacks properties like naturalWidth or naturalHeight, which belong to an imageElement.

This discrepancy is what triggers the 'Value is not of type 'long'' error message.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Insert a new <tr> element into a dynamic table using PHP and jQuery without the need to refresh the page

I am attempting to dynamically insert a row into an existing table when a button is clicked. The rows in the table are created dynamically based on data retrieved from a PHP script. My approach involves making an ajax call to the insert_tr.php script, whi ...

The React Bootstrap modal fails to display the value of an argument passed through a parameter

I am currently working on a project that utilizes React for its front end development. Below is the code snippet: import React, {useState} from 'react'; import Tree from 'react-d3-tree'; import { useCenteredTree } from "./helpers&q ...

When trying to pass 3 parameters from an Angular frontend to a C# MVC backend, I noticed that the server side was receiving null

I have encountered an issue where I am attempting to pass 3 parameters (2 types and one string) but they are showing up as null on the server side. Below is my service: const httpOptions = { headers: new HttpHeaders({ 'Content-Type&ap ...

Modify the value of a variable every 250 milliseconds

Currently working on a game website and stuck at the registration stage. We are looking to allow players to input a code in their Ingame notes for verification purposes. I have created a PHP class to retrieve the ingame notes, but now I need to set a java ...

Tips for monitoring password and password confirmation fields in DevTools when using AngularJS forms

Within the ng-model, I have identified two variables: vm.user.password and vm.confirmpassword. The input fields are equipped with attributes such as id, name, and class. I am interested in monitoring both the password and confirmpassword values within Dev ...

Form submission is not functioning as expected

I am having trouble with my form submission. When I try to submit the form, nothing happens. I have tried various solutions but have not been able to resolve the issue. I have reviewed all available resources but still cannot figure out why my code is not ...

Tips for making an ajax call in Angular 6

As a backend developer, I have limited experience with Angular. How can I send an ajax request from Angular to test my API? The request needs to be sent before clearing the localeStorage. Can you provide guidance on how to achieve this? <button (clic ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

ESLint is parsing through alternative configurations

My .eslintrc file is very simple: { "extends": [ "twilio" ] } However, when I run eslint, I encounter this error message: The config "standard" was referenced from the config file in "/Users/MyAccount/Projects/my-sample-app/node_modules/cipher ...

What is the proper method for triggering an animation using an IF statement with A-Frame animation mixer?

I am currently exploring the capabilities of the animation mixer in A-Frame and trying to trigger a specific action when a particular animation is playing (like Animation 'B' out of A, B, C). Although I'm not well-versed in Javascript, I ha ...

Using the `await` command may lead to the variable losing its scope

Utilizing the await keyword to retrieve data from the database has been causing me some trouble. The variable secuity_ok is set to true on one line, but inexplicably changes to false on the following line. What could be causing this issue? It's worth ...

Issues with looping in Internet Explorer 8

Hey, I'm having an issue with this JavaScript function: function test(){ var count = 0; var date1 = $('#alternatestartdate').val(); var date2 = $('#alternateenddate').val(); ...

Storing the information filled out in the form and utilizing it to navigate to the correct destination URL

With the generous assistance and insightful advice from members of Stack Overflow, I am nearing completion of my quiz project. However, I do have a few lingering questions regarding some final touches needed for the project. Before delving into those quest ...

Angular Bootstrap notifications will stay open indefinitely and will not automatically dismiss after a certain period

I need help with adding alerts using Angular Bootstrap that should dismiss themselves after a certain timeout. However, the alerts are not dismissing on their own. Here's the code snippet: angular.module('ui.services').service('AlertSe ...

When interacting with the iframe in an Ionic3 app, it suddenly crashes

Greetings! I have integrated a flipping book URL inside an iframe: <ng-container> <iframe [src]="eUrl" id="flipping_book_iframe" frameborder="0" allowfullscreen="allowfullsc ...

When attempting to render mathML in a canvas on Safari, the image load callback does not properly trigger, resulting in

I am currently working on rendering mathML into an HTML5 canvas. One suggestion I received was to embed the mathML as an SVG foreign object, render it into an image, and then display the image within the canvas. However, this method works fine in Firefox ...

Is there a way to have the span update even if the input stays the same? Currently, it only changes when the input is different

Retrieve results of 3 lines (Ps) by entering a word in the text area and clicking search. If the word is found after clicking the button, a span will be displayed with the count of occurrences as well as the highlighted P(s) where it was found. If the wo ...

Guide on pre-selecting an option in a select control using Angular

I need some assistance with the following: My select control is defined as shown below, and I populate its options with strings from an array of strings in my component named tools.Attributes.Serials. Everything is functioning correctly: <select class= ...

The Chrome extension takes control of the new tab feature by redirecting it to a custom newtab.html

I have a website https://example.com where users can adjust their site preferences, including enabling night mode. To enhance the user experience, I developed a Chrome extension for https://example.com that transforms Chrome's new tab with a custom ne ...