Best JavaScript code snippet using wpt
index.ts
Source: index.ts
1import { chunk, clone, sum } from 'lodash-es';2import { v4 } from 'uuid';3import * as fnv1a from '@sindresorhus/fnv1a';4const canvas = document.getElementById('canvas');5const ctx = (canvas as HTMLCanvasElement).getContext('2d');6const imgCanvas = document.getElementById('imgcanvas');7let imgCtx = (imgCanvas as HTMLCanvasElement).getContext('2d');8const loadImage = async (src: string) => {9 const imgCanvas = document.getElementById('imgcanvas');10 imgCtx = (imgCanvas as HTMLCanvasElement).getContext('2d');11 imgCtx.imageSmoothingEnabled = false;12 await new Promise((resolve, reject) => {13 try {14 const image = new Image();15 image.onload = () => {16 imgCtx.canvas.height = image.naturalHeight;17 imgCtx.canvas.width = image.naturalWidth;18 imgCtx.setTransform(1,0,0,1,0,0);19 imgCtx.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight);20 resolve(true);21 };22 image.onerror = (e) => { reject(e); }23 image.src = src;24 } catch (err) {25 reject(err);26 }27 })28 return imgCtx;29}30const percent = 0.2;31const draw = (ctx: CanvasRenderingContext2D, item: any, col: number, row: number) => {32 ctx.fillStyle = `rgba(${ item[0]},${ item[1] },${ item[2]}, 1.0`;33 ctx.fillRect(col, row, 1, 1);34}35function swap(items:any, leftIndex: any, rightIndex: any){36 let temp = items[leftIndex];37 draw(ctx, items[leftIndex], leftIndex % ctx.canvas.width, Math.floor(leftIndex / ctx.canvas.width))38 draw(ctx, items[rightIndex], rightIndex % ctx.canvas.width, Math.floor(rightIndex / ctx.canvas.width))39 items[leftIndex] = items[rightIndex];40 items[rightIndex] = temp;41}42const compIndex = (index: number, items: any) => sum(items[index]);43function partition(items: any, left: any, right: any) {44 const pivotIndex = Math.floor((right + left) / 2);45 let pivot = compIndex(pivotIndex, items);46 let i = left; //left pointer47 let j = right; //right pointer48 while (i <= j) {49 while (compIndex(i, items) < pivot) { i++; }50 while (compIndex(j, items) > pivot) { j--; }51 if (i <= j) { swap(items, i, j); i++; j--; }52 }53 return i;54}55async function quickSort(items: any, left: any, right:any, intervalId: string) {56 var index: number;57 if (items.length > 1) {58 if (intervalId !== currentId) { return items; }59 index = partition(items, left, right);60 if (left < index - 1) { requestAnimationFrame(() => quickSort(items, left, index - 1, intervalId)); }61 if (index < right) { requestAnimationFrame(() => quickSort(items, index, right, intervalId)); }62 }63 return items;64}65let currentId: string;66const main = async () => {67 const video = document.createElement('video');68 video.src = './bird.webm';69 video.muted = true;70 video.addEventListener('loadeddata', () => {71 video.oncanplay = function() {72 video.play();73 };74 })75 let interval: NodeJS.Timer;76 // video.addEventListener('play', async () => {77 // ctx.canvas.width = (video as HTMLVideoElement).videoWidth;78 // ctx.canvas.height = (video as HTMLVideoElement).videoHeight;79 // ctx.imageSmoothingEnabled = false;80 // ctx.setTransform(1,0,0,1,0,0);81 // imgCtx.canvas.width = (video as HTMLVideoElement).videoWidth;82 // imgCtx.canvas.height = (video as HTMLVideoElement).videoHeight;83 // imgCtx.imageSmoothingEnabled = false;84 // imgCtx.setTransform(1,0,0,1,0,0);85 // clearInterval(interval);86 // interval = setInterval(async () => {87 // let id = v4();88 // currentId = id;89 // imgCtx.drawImage(video as HTMLVideoElement, 0, 0, imgCtx.canvas.width, imgCtx.canvas.height);90 // const imageData = imgCtx.getImageData(0,0, imgCtx.canvas.width, imgCtx.canvas.height).data;91 // let pixelData = chunk(imageData as any, 4);92 // pixelData = await quickSort(pixelData, 0, pixelData.length - 1, id);93 // }, 100);94 // }, false);95 console.log('yo')96 video.addEventListener('play', () => {97 ctx.canvas.width = (video as HTMLVideoElement).videoWidth;98 ctx.canvas.height = (video as HTMLVideoElement).videoHeight;99 ctx.imageSmoothingEnabled = false;100 ctx.setTransform(1,0,0,1,0,0);101 imgCtx.canvas.width = (video as HTMLVideoElement).videoWidth;102 imgCtx.canvas.height = (video as HTMLVideoElement).videoHeight;103 imgCtx.imageSmoothingEnabled = false;104 imgCtx.setTransform(1,0,0,1,0,0);105 clearInterval(interval);106 const bloomFilters = {107 r: new Map(),108 g: new Map(),109 b: new Map(),110 }111 interval = setInterval(async () => {112 imgCtx.drawImage(video as HTMLVideoElement, 0, 0, imgCtx.canvas.width, imgCtx.canvas.height);113 const imageData = imgCtx.getImageData(0,0, imgCtx.canvas.width, imgCtx.canvas.height).data;114 let pixeldata = chunk(imageData, 4);115 116 const len = Math.floor(pixeldata.length );117 const set = (map ,hash, value) => {118 if (map.has(hash)) {119 // map.set(hash, Math.floor(map.get(hash) +value) / 2));120 // map.set(hash, Math.floor((map.get(hash) +value) / 2));121 map.set(hash, Math.max(map.get(hash), value));122 } else {123 map.set(hash, value);124 }125 };126 pixeldata.forEach((data, i) => {127 set(bloomFilters.r, fnv1a(i.toString()) % len , data[0])128 set(bloomFilters.g, fnv1a(i.toString()) % len , data[1])129 set(bloomFilters.b, fnv1a(i.toString()) % len , data[2])130 });131 // const multiplier = Math.floor(Math.random() * 100)132 const multiplier = 1;133 pixeldata.forEach((data, i) => {134 draw(135 ctx,136 [137 bloomFilters.r.get(fnv1a(data[0].toString()) % len) * multiplier % 255,138 bloomFilters.g.get(fnv1a(data[1].toString()) % len) * multiplier % 255,139 bloomFilters.b.get(fnv1a(data[2].toString()) % len) * multiplier % 255,140 // bloomFilters.r[fnv1a(i.toString()) % len],141 // bloomFilters.g[fnv1a(i.toString()) % len],142 // bloomFilters.b[fnv1a(i.toString()) % len],143 data[3]144 ],145 i % ctx.canvas.width,146 Math.floor(i / ctx.canvas.width)147 );148 });149 },5);150 })151};...
detection-on-worker.https.worker.js
1importScripts("/resources/testharness.js");2importScripts("resources/shapedetection-helpers.js");3'use strict';4// These tests verify that a Detector's detect() works on an5// ImageBitmap on workers.6const imageBitmapTests =7 [8 {9 createDetector: () => { return new FaceDetector(); },10 mockTestName: "FaceDetectionTest",11 resultSize: 3, // Number of faces12 detectorType: "Face"13 },14 {15 createDetector: () => { return new BarcodeDetector(); },16 mockTestName: "BarcodeDetectionTest",17 resultSize: 2, // Number of barcodes18 detectorType: "Barcode"19 }20 ];21for (let imageBitmapTest of imageBitmapTests) {22 // ImageBitmap is of transferable type and can be sent to and23 // tested on worker.24 detection_test(imageBitmapTest.mockTestName, async (t, detectionTest) => {25 const img = createTestImage();26 const theImageBitmap = await createImageBitmap(img);27 const detector = imageBitmapTest.createDetector();28 const detectionResult = await detector.detect(theImageBitmap);29 assert_equals(detectionResult.length, imageBitmapTest.resultSize,30 `Number of ${imageBitmapTest.detectorType}`);31 }, `${imageBitmapTest.detectorType} Detector detect(ImageBitmap) on worker`);32}33function createTestImage() {34 const image = new OffscreenCanvas(100, 50);35 const imgctx = image.getContext('2d');36 imgctx.fillStyle = "#F00";37 imgctx.fillRect(0, 0, 2, 2);38 imgctx.fillStyle = "#0F0";39 imgctx.fillRect(0, 0, 1, 1);40 return image;41}...
drawImage.ts
Source: drawImage.ts
1import { Vec2 } from "../lib/physics";2export type ImgCtx = {3 img: CanvasImageSource,4 x: number,5 y: number,6 offset: Vec2,7 w: number,8 h: number,9 flipH: boolean10 rotate: number11}12export function drawImage(cctx: CanvasRenderingContext2D, imgCtx: ImgCtx) {13 cctx.save();14 // move to the center of the canvas15 cctx.translate(imgCtx.x, imgCtx.y)16 // rotate the canvas to the specified degrees17 cctx.rotate(imgCtx.rotate * Math.PI / 180);18 cctx.translate(-imgCtx.x, -imgCtx.y)19 // draw the image20 if (imgCtx.flipH) drawImageFlipHorizontally(cctx, imgCtx.img, imgCtx.x - imgCtx.offset.x, imgCtx.y + imgCtx.offset.y, imgCtx.w, imgCtx.h)21 else cctx.drawImage(imgCtx.img, imgCtx.x + imgCtx.offset.x, imgCtx.y + imgCtx.offset.y, imgCtx.w, imgCtx.h)22 cctx.restore();23}24export function drawImageFlipHorizontally(cctx: CanvasRenderingContext2D, img: CanvasImageSource, x: number, y: number, w: number, h: number) {25 // move to x + img's width26 cctx.translate(x + Number(img.width), y);27 // scaleX by -1; this "trick" flips horizontally28 cctx.scale(-1, 1);29 // draw the img30 // no need for x,y since we've already translated31 cctx.drawImage(img, 0, 0, w, h);32 // always clean up -- reset transformations to default33 cctx.setTransform(1, 0, 0, 1, 0, 0);...
Using AI Code Generation
1var imgctx = require('imgctx');2image.save('logo.png', 'png');3image.save('logo.jpg', 'jpg');4image.save('logo.gif', 'gif');5image.save('logo.bmp', 'bmp');6image.save('logo.tiff', 'tiff');7var imgctx = require('imgctx');8image.save('logo.png', 'png');9image.save('logo.jpg', 'jpg');10image.save('logo.gif', 'gif');11image.save('logo.bmp', 'bmp');12image.save('logo.tiff', 'tiff');13var imgctx = require('imgctx');14image.save('logo.png', 'png');15image.save('logo.jpg', 'jpg');16image.save('logo.gif', 'gif');17image.save('logo.bmp', 'bmp');18image.save('logo.tiff', 'tiff');19var imgctx = require('imgctx');20image.save('logo.png', 'png');21image.save('logo.jpg', 'jpg');22image.save('logo.gif', 'gif');23image.save('logo.bmp', 'bmp');24image.save('logo.tiff', 'tiff');25var imgctx = require('imgctx');26image.save('logo.png', 'png');27image.save('logo.jpg', 'jpg');28image.save('logo.gif', 'gif');29image.save('logo.bmp', 'bmp');30image.save('logo.tiff', 'tiff');31var imgctx = require('imgctx');32image.save('logo.png', 'png');33image.save('logo.jpg', 'jpg');34image.save('logo.gif', 'gif');
Check out the latest blogs from LambdaTest on this topic:
API (Application Programming Interface) is a set of definitions and protocols for building and integrating applications. It’s occasionally referred to as a contract between an information provider and an information user establishing the content required from the consumer and the content needed by the producer.
Lack of training is something that creates a major roadblock for a tester. Often, testers working in an organization are all of a sudden forced to learn a new framework or an automation tool whenever a new project demands it. You may be overwhelmed on how to learn test automation, where to start from and how to master test automation for web applications, and mobile applications on a new technology so soon.
JavaScript is one of the most widely used programming languages. This popularity invites a lot of JavaScript development and testing frameworks to ease the process of working with it. As a result, numerous JavaScript testing frameworks can be used to perform unit testing.
Have you ever visited a website that only has plain text and images? Most probably, no. It’s because such websites do not exist now. But there was a time when websites only had plain text and images with almost no styling. For the longest time, websites did not focus on user experience. For instance, this is how eBay’s homepage looked in 1999.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!