|
| 1 | +import { expect, test, describe } from "vitest"; |
| 2 | +import { Jimp } from "./index.js"; |
| 3 | + |
| 4 | +describe("Canvas", () => { |
| 5 | + test("should be able to create a Jimp from a canvas", async () => { |
| 6 | + const canvas = document.createElement("canvas"); |
| 7 | + const ctx = canvas.getContext("2d")!; |
| 8 | + |
| 9 | + // make all the pixels red |
| 10 | + ctx.fillStyle = "red"; |
| 11 | + ctx.fillRect(0, 0, canvas.width, canvas.height); |
| 12 | + |
| 13 | + const beforeValue = ctx.getImageData(0, 0, canvas.width, canvas.height) |
| 14 | + .data[0]; |
| 15 | + |
| 16 | + const image = await Jimp.fromBitmap( |
| 17 | + ctx.getImageData(0, 0, canvas.width, canvas.height) |
| 18 | + ); |
| 19 | + |
| 20 | + // The jimp image is red |
| 21 | + expect(image.bitmap.data[0]).toBe(255); |
| 22 | + expect(image.bitmap.data[1]).toBe(0); |
| 23 | + expect(image.bitmap.data[2]).toBe(0); |
| 24 | + expect(image.bitmap.data[3]).toBe(255); |
| 25 | + |
| 26 | + // Modify the image |
| 27 | + image.greyscale(); |
| 28 | + |
| 29 | + const imageData = new ImageData( |
| 30 | + new Uint8ClampedArray(image.bitmap.data), |
| 31 | + image.bitmap.width, |
| 32 | + image.bitmap.height |
| 33 | + ); |
| 34 | + |
| 35 | + // Write back to the canvas |
| 36 | + ctx.putImageData(imageData, 0, 0); |
| 37 | + |
| 38 | + // The canvas should have changed |
| 39 | + expect(beforeValue).not.toBe( |
| 40 | + ctx.getImageData(0, 0, canvas.width, canvas.height).data[0] |
| 41 | + ); |
| 42 | + }); |
| 43 | +}); |
0 commit comments