gpt4 book ai didi

javascript - 如何选择 HTML5 Canvas 形状?

转载 作者:太空宇宙 更新时间:2023-11-04 14:45:18 25 4
gpt4 key购买 nike

我有一个 HTML5 Canvas ,我在上面画了几个形状。

我想要发生的是,当鼠标在任何形状上单击时,应该选择该形状(至少它可以告诉您选择了哪种形状)。

谢谢。

最佳答案

尝试使用现有的 Canvas 库(或创建您自己的 Canvas 库),该库在选择形状时具有事件。

下面的例子使用了 Kinetic JS library , 下面的例子来自 HTML5 Canvas Region Events Example :

var triangle = new Kinetic.Shape(function(){
var context = this.getContext();
context.beginPath();
context.lineWidth = 4;
context.strokeStyle = "black";
context.fillStyle = "#00D2FF";
context.moveTo(120, 50);
context.lineTo(250, 80);
context.lineTo(150, 170);
context.closePath();
context.fill();
context.stroke();
});

triangle.on("mouseout", function(){
writeMessage(messageLayer, "Mouseout triangle");
});

triangle.on("mousemove", function(){
var mousePos = stage.getMousePosition();
var x = mousePos.x - 120;
var y = mousePos.y - 50;
writeMessage(messageLayer, "x: " + x + ", y: " + y);
});

shapesLayer.add(triangle);

var circle = new Kinetic.Shape(function(){
var canvas = this.getCanvas();
var context = this.getContext();
context.beginPath();
context.arc(380, canvas.height / 2, 70, 0, Math.PI * 2, true);
context.fillStyle = "red";
context.fill();
context.lineWidth = 4;
context.stroke();
});

circle.on("mouseover", function(){
writeMessage(messageLayer, "Mouseover circle");
});
circle.on("mouseout", function(){
writeMessage(messageLayer, "Mouseout circle");
});
circle.on("mousedown", function(){
writeMessage(messageLayer, "Mousedown circle");
});
circle.on("mouseup", function(){
writeMessage(messageLayer, "Mouseup circle");
});

shapesLayer.add(circle);

stage.add(shapesLayer);
stage.add(messageLayer);


此外,如果光标在形状内,我还包括一些鼠标进入检测,而不使用任何 javascript 库。

基于矩形的鼠标进入检测:

function isCursorWithinRectangle(x, y, width, height, mouseX, mouseY) {
if(mouseX > x && mouseX < x + width && mouseY > y && mouseY < y + height) {
return true;
}
return false;
}


基于圆圈的鼠标进入检测:

function isCursorWithinCircle(x, y, r, mouseX, mouseY) {
var distSqr = Math.pow(x - mouseX, 2) + Math.pow(y - mouseY, 2);

if(distSqr < r * r) {
return true;
}
return false;
}

关于javascript - 如何选择 HTML5 Canvas 形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8905247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com