我正在设计一个包含大量数学图形的网页。例如菱形、正方形、矩形、三 Angular 形等....
我想要实现的是,当我点击任何一个数字时,它应该显示一个 msg/info 之类的东西。
我只有一个 Canvas ID,里面有很多图形,我如何让它们可点击以便我可以显示每个图形所需的信息
最佳答案
以下是如何使用原生 html Canvas 让用户获得有关他们单击的形状的消息:
- 对于每个形状,将它们的 Angular 点放在一个 javascript 对象中
- 将所有这些形状对象放在一个数组中
- 监听 mousedown 事件
- 在 mousedown 中使用 context.isPointInPath 检查鼠标是否在每个形状内
- 如果鼠标在对象内部,则显示有关该形状的消息
演示:http://jsfiddle.net/m1erickson/wPMk5/
示例代码:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
// canvas variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
// set styles
ctx.fillStyle="skyblue";
ctx.strokeStyle="lightgray";
ctx.lineWidth=2;
// create a triangle and parallelogram object
var triangle={
points:[{x:25,y:100},{x:50,y:50},{x:75,y:100}],
message:"I am a triangle"
}
var parallelogram={
points:[{x:150,y:50},{x:250,y:50},{x:200,y:100},{x:100,y:100}],
message:"I am a parallelogram"
}
// save the triangle and parallelogram in a shapes[] array
var shapes=[];
shapes.push(triangle);
shapes.push(parallelogram);
// function to draw (but not fill/stroke) a shape
// (needed because isPointInPath only tests the last defined path)
function define(shape){
var points=shape.points;
ctx.beginPath();
ctx.moveTo(points[0].x,points[0].y);
for(var i=1;i<points.length;i++){
ctx.lineTo(points[i].x,points[i].y);
}
}
// function to display a shape on the canvas (define + fill + stroke)
function draw(shape){
define(shape);
ctx.fill();
ctx.stroke();
}
// display the triangle and parallelogram
draw(triangle);
draw(parallelogram);
// called when user clicks the mouse
function handleMouseDown(e){
e.preventDefault();
// get the mouse position
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
// iterate each shape in the shapes array
for(var i=0;i<shapes.length;i++){
var shape=shapes[i];
// define the current shape
define(shape);
// test if the mouse is in the current shape
if(ctx.isPointInPath(mouseX,mouseY)){
// if inside, display the shape's message
alert(shape.message);
}
}
}
// listen for mousedown events
$("#canvas").mousedown(function(e){handleMouseDown(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
关于javascript - 如何使html中的canvas元素可点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22317805/