elle_C
November 10, 2022, 2:25pm
1
Hello, I’m new to p5 DOM manipulation and I’m trying to discover if it’s possible to associate an object with a link. For example I would like to draw a circle and when it is clicked I go to a link.
I have experimented with instance mode and seen how I can link an entire canvas to a html anchor link, this is nice to make individual ‘buttons’ however now I want to know if I can have just one canvas with associated buttons e.g. an arrangement of circles where each circle is a different link.
Thanks in advance for an help!
josephh
November 10, 2022, 11:00pm
2
Hi @elle_C ,
Welcome to the forum!
A simple solution might be to do that in pure JavaScript using the window.location
object and simulating a link hovering effect:
class LinkCircle {
constructor(x, y, diameter, url) {
this.x = x;
this.y = y;
this.diameter = diameter;
this.url = url;
}
isMouseInside() {
return dist(this.x, this.y, mouseX, mouseY) < this.diameter / 2.0;
}
mousePressed() {
if (this.isMouseInside()) {
window.location.assign(this.url);
}
}
display() {
const mouseInside = this.isMouseInside();
// Simulate link hover by changing cursor type
cursor(mouseInside ? HAND : ARROW);
fill(mouseInside ? 255 : 0);
circle(this.x, this.y, this.diameter);
}
}
let linkCircle;
function setup() {
createCanvas(400, 400);
linkCircle = new LinkCircle(
width / 2, height / 2, 250,
"https://processing.org"
);
}
function draw() {
background(220);
linkCircle.display();
}
function mousePressed() {
linkCircle.mousePressed();
}
Otherwise, since p5js uses the native HTML <canvas>
element to draw things it’s not really possible to use HTML links with canvas shapes.
You might want to use SVG instead or CSS: The Many Ways to Link Up Shapes and Images with HTML and CSS | CSS-Tricks - CSS-Tricks
1 Like
elle_C
November 11, 2022, 4:55pm
3
Hi @josephh ,
Thank you so much for your great insight! As a beginner it really helps to know the different options there are.
I like the idea of the javascript/class option as it will give me alot of freedom to make and arrange my visual links - I’m going to give it a try
1 Like
josephh
November 11, 2022, 6:22pm
4
Gad it helped! A good option might be to use class inheritance to implement any kind of shapes you want with a specific click bounding box.