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

Animating CSS using JavaScript

Recently diving into the world of JavaScript, I've taken on the challenge of creating an analog clock. I began by crafting the second hand using CSS but now I'm eager to transition it to Javascript without relying on jQuery or any other JS framew ...

Add option button

Is there a way to dynamically add radio buttons using jQuery or JavaScript and save the data into a database? I have successfully appended input types such as text, textarea, checkbox, and select with options. Here is my code: <!DOCTYPE html> < ...

JavaScript, keep it easy: globalize

Looking for help with a simple regex expression... document.getElementById('testing').value=f2.innerHTML.replace(">",">\n"); I'm having an issue where it only stops after the first line break. How can I make it work for the enti ...

Getting the input from an HTML editor and inserting it into a textarea using JavaScript

Currently, I am in the process of developing an HTML editor for a project. I have downloaded a program online that I am attempting to customize according to my requirements. However, I am encountering difficulties when trying to retrieve the inner HTML of ...

Generating a primary XML element encompassing multiple namespaces

I am currently working on integrating Restful services with Backbone.js framework. In this project, I need to send XML data and add multiple namespaces to it. Here is the snippet of my current JavaScript code: var mainNamespace = "xmlns='http://serv ...

Is it possible to change the inner html to null during an active ajax request?

My goal is to have two separate data.html files inserted into two different HTML files without needing a click event. I want the structure of my data.html files to remain consistent, while allowing the template of my website to change dynamically by callin ...

Is there a way to customize jqwidgets jQuery grid cell classes/styles based on row ID and column name?

{ text: 'sell', datafield: 'Sales', width: '3%', columntype: 'button', filterable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { return &apos ...

Is using float:right making the jquery slide toggle dropdown div (triggered by hover) appear glitchy?

Utilizing jQuery's slidetoggle and hover functions, I have successfully implemented a dropdown feature in my div. Within this div, there is various information displayed including the date, a note counter, and three buttons. The first two are Tumblr ...

Exploring JSON API Data with Vue Js

While working on my Vue Js project, I encountered an issue with displaying data from an API in JSON format. Despite using this.obj =JSON.stringify(this.Flats); and successfully seeing all the data using console.log, I struggled to loop over and view the pa ...

The ng-repeat function is iterating through the array multiple times

Using ng-repeat to bind the same array multiple times. JavaScript : $scope.currentitem = item; $scope.currentitemCategory = $scope.currentitem.category.split(','); console.log($scope.currentitemCategory); HTML: <div ng-repea ...

Tips for accessing cart values when navigating to a different view in AngularJS

Hi, I'm currently working on a project involving a shopping cart. The project includes various categories with different products within each category. When adding a product to the cart from one category, it displays correctly. Likewise, adding anot ...

Ways to easily modify images using a single button with the help of jq

I am new to programming and eager to learn... Currently, I am facing the following problem: I would like to create a functionality where three images can be changed using one button and incorporating fadeIn and fadeOut animations. Essentially, all images ...

How to open a print preview in a new tab using Angular 4

Currently, I am attempting to implement print functionality in Angular 4. My goal is to have the print preview automatically open in a new tab along with the print popup window. I'm struggling to find a way to pass data from the parent window to the c ...

Simultaneously updating the states in both the child and parent components when clicked

In my code, I have two components: the parent component where a prop is passed in for changing state and the child component where the function is called. The function changes the state of the parent component based on an index. changeState={() => this ...

Convert an object to a custom array using JavaScript

I need to transform the following object: "age": [ { "Under 20": "14", "Above 40": "1" } ] into this structure: $scope data = {rows:[ {c: [ {v: "Under 20"}, {v: 14} ]}, {c: [ {v: "Above 40"}, ...

Is there a way to personalize the chart tooltip in jqplot to fit my preferences?

I have a chart that displays data. I would like the x-axis labels to show in the format MM/DD, and in the tooltip, I want to display data in the format HH:y-axis. For example, in the chart below, I want the x-axis labels to be 'Oct 15','Oct ...

`How can I eliminate all duplicate entries from an array of objects in Angular?`

arr = new Array(); arr.push({place:"1",name:"true"}); arr.push({place:"1",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"3",name:"false"}); arr.push({place:"3",name:"true"}); I'm curious about ...

Error: The function **now.toUTCString** is not recognized and cannot be executed by HTMLButtonElement

While the JavaScript code runs smoothly without setting a time zone, I encountered an error when trying to display the Barbados time zone. The issue is related to now.toUTCString function throwing the following error message. How can I resolve this? Uncau ...

Building User-Friendly Tabs with Twitter Bootstrap: Add or Remove Tabs and Content on the Fly

Looking forward to any assistance or suggestions... I am utilizing Twitter Bootstrap tabs for organizing information on a form page. Each tab will contain a "contact form" where users can add multiple contacts before submitting the entire form. <div c ...

Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" fo ...