PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 27, 2022

[FIXED] How can I crop an image in p5.js without drawing image on the screen

 July 27, 2022     crop, image, javascript, p5.js     No comments   

Issue

I've researched and found that you can "crop" an image by using get(), but the image has to be drawn on the screen where you then take a section of the canvas. Is it possible to load an image then save a cropped version of it in a variable? So maybe something like this:

var img;
var cropped;

function preload(){
  img = imageLoad('dog.png', crop)
}

function crop(image){
  cropped = crop(img, 0, 0, img.w/2, img.h) // Getting left half of image 
}

Thank you.


EDIT: This is the function I made using copy(), but I don't know if there's an easier way that I'm missing.

function crop(image, x, y, w, h) {
  var cropped = createImage(w, h);
  cropped.copy(image, x, y, x + w, y + h, 0, 0, x + w, y + h)
  return cropped;
}

Solution

You can access the pixels of an image directly. You don't have to draw it to the canvas first.

Start by reading through the P5.Image reference.

At a high level, what you want to do is create a new graphics (the createGraphics() function is your friend, and then draw the section of the image you want to that graphics. Whether you draw the image or the graphics to the canvas is up to you.



Answered By - Kevin Workman
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing