I am trying to write a stamp tool function that can upload an image as a stamp. Unfortunately, I am unable to scale the image as a stamp size. For example. the image remains the original size but the stamp size is 50x50. Therefore, the stamp can only show the top left corner of the image.
I tried to use the size or resize function in P5js but it doesn't work.
I initialise a global variable called "stamp" and the size.
stamp = loadImage('./stamps/star.png');
this.size = 50;
In the P5JS draw function
image(stamp, mouseX, mouseY, this.size, this.size);
In my handleFile function
var handleFile = function (file) {
print(file);
if (file.type === 'image') {
var targetStamp = createDiv();
targetStamp.class('stamps');
newStamp = createImg(file.data, '', () => { newStamp.size(100, AUTO) });
targetStamp.child(newStamp);
stampSelector = select(".stampSelector");
stampSelector.child(targetStamp);
targetStamp.mouseClicked(function () {
var items = selectAll(".stamps");
for (var i = 0; i < items.length; i++) {
items[i].style('border', '0')
}
targetStamp.style("border", "2px solid blue");
stamp = newStamp;
})
} else {
img = null;
}
}
The size is succeeded to change by CSS, but cannot use as a stamp. Anyone can help please.
When you say "cannot use as a stamp" it is not clear what the problem is. With a simplified version of your code it generally seems to work. However, it would appear that there is a bug with how the image() function handles source <img> elements that have been resized (it crops the source to the specified size, instead of using the original image dimensions, even when you explicitly specify source dimensions). There is a workaround though: using a CSS transform to control the size of the <img> element.
let img;
let size = 50;
function setup() {
createCanvas(400, 400);
let input = createFileInput(handleFile);
input.position(10, 10);
noLoop();
background(0);
}
function draw() {}
function mouseClicked() {
if (img) {
image(img, mouseX, mouseY, size, size);
}
}
function handleFile(file) {
if (file.type === "image") {
img = createImg(file.data, "uploaded image", "anonymous", () => {
// This resizes the <img> tag, but will not effect the size of the image when drawn.
// img.size(100, AUTO);
img.style('transform', `scale(${100 / img.width})`);
img.style('transform-origin', 'top left');
});
} else {
img = null;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>