简体   繁体   中英

How to create upload in each hexagon shape in canvas?

I create multi shape with canvas, but I want to upload a photo by clicking on each hexagon.

How to create with jquery?

 const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const a = 2 * Math.PI / 6; const r = 50; // 1st x = r; y = r; drawHexagon(x, y); // 2nd x = x + r + r * Math.cos(a); y = y + r * Math.sin(a); drawHexagon(x, y); // 3rd x = x + r + r * Math.cos(a); y = y - r * Math.sin(a); drawHexagon(x, y); // 4th x = x + r + r * Math.cos(a); y = y + r * Math.sin(a); drawHexagon(x, y); function drawHexagon(x, y) { ctx.beginPath(); for (var i = 0; i < 6; i++) { ctx.lineTo(x + r * Math.cos(a * i), y + r * Math.sin(a * i)); } ctx.closePath(); ctx.stroke(); }
 <canvas id="canvas" width="800" height="500" />

I'm going to answer the first part of your problem...
The comment from ggorlen is spot on, you have a complex situation, you must break down into multiple questions and tackle each individually

So how do we detect the mouse is over a particular shape in a canvas?
My recommendation use Path2D:
https://developer.mozilla.org/en-US/docs/Web/API/Path2D
It comes with a handy function isPointInPath to detect if a point is in or path:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath

Sample code below, I'm using the mouse move event but you can use any other:

 const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); class Hexagon { constructor(x, y, r, a) { this.path = new Path2D() for (var i = 0; i < 6; i++) { this.path.lineTo(x + r * Math.cos(a), y + r * Math.sin(a)); a += Math.PI/3 } } draw(evt) { ctx.beginPath() var rect = canvas.getBoundingClientRect() var x = evt.clientX - rect.left var y = evt.clientY - rect.top ctx.fillStyle = ctx.isPointInPath(this.path, x, y)? "red": "green" ctx.fill(this.path) } } shapes = [] shapes.push(new Hexagon( 50, 50, 40, 0)) shapes.push(new Hexagon(125, 90, 45, 0.5)) shapes.push(new Hexagon(200, 50, 30, 0.8)) shapes.push(new Hexagon(275, 90, 53, 1)) canvas.addEventListener("mousemove", function(evt) { ctx.clearRect(0, 0, canvas.width, canvas.height) shapes.forEach((s) => s.draw(evt)) } ) shapes.forEach((s) => s.draw({ clientX: 0, clientY: 0 }))
 <canvas id="canvas" width="400" height="180" />

I hardcoded your constants to keep this example as small as possible
Also my class Hexagon takes the radius and angle as parameters that way we can have different Hexagons see: constructor(x, y, r, a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM