繁体   English   中英

如何在 canvas 中的每个六边形中创建上传?

[英]How to create upload in each hexagon shape in canvas?

我用 canvas 创建多形状,但我想通过单击每个六边形来上传照片。

如何用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" />

我要回答你问题的第一部分......
ggorlen的评论是正确的,你的情况很复杂,你必须分解成多个问题并单独解决每个问题

那么我们如何检测鼠标在 canvas 中的特定形状上呢?
我的建议使用 Path2D:
https://developer.mozilla.org/zh-CN/docs/Web/API/Path2D
它带有一个方便的 function isPointInPath 来检测一个点是否在或路径中:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath

下面的示例代码,我使用的是鼠标移动事件,但您可以使用任何其他事件:

 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" />

我硬编码了你的常量以使这个例子尽可能小
我的class Hexagon也将半径和角度作为参数,这样我们就可以拥有不同的 Hexagon 参见: constructor(x, y, r, a)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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