Hello. I’m currently making a program where I need to get a section of an image and save it to a given variable. The problem is that ‘get()’ only works on p5.Image objects and when I try to use it on an image created by the ‘createImg()’ function, I get a “.get is not a function” error.
Note: the ‘copy()’ function doesn’t do the work for me. I’ve also unsuccessfully tried to make the createImg() image a child of the p5.Image class.
function setup() {
const canvas = createCanvas(500, 500);
let img = createImg(
"https://p5js.org/assets/img/asterisk-01.png",
"the p5 magenta asterisk"
);
const offScreenCanvas = createGraphics(img.width, img.height);
offScreenCanvas.drawingContext.drawImage(img.elt, 0, 0);
const region = offScreenCanvas.get(0, 0, 50, 50);
image(region, 0, 0);
}
function draw() {
noLoop();
}
But you can also have both loadImage and createImage with the preload() function that will wait for the image to download (and you won’t load it twice since it’s cached):
let img, imgDOM;
const imageURL =
"https://images.pexels.com/photos/14139354/pexels-photo-14139354.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2";
function preload() {
img = loadImage(imageURL);
}
function setup() {
const canvas = createCanvas(500, 500);
imgDOM = createImg(imageURL, "web image");
const region = img.get(0, 0, 50, 50);
image(region, 0, 0);
}
function draw() {
noLoop();
}