使用单击选项在画布中绘制圆圈

时间:2013-10-09 14:11:05

标签: javascript jquery html5 canvas

我写了这个javascript代码:

<script>
        var canvas = document.getElementById("canvas");
        var canvasOffset = $("#canvas").offset();
        var offsetX = canvasOffset.left;
        var offsetY = canvasOffset.top;

        function handleMouseDown(e) {
            mouseX = parseInt(e.clientX - offsetX);
            mouseY = parseInt(e.clientY - offsetY);
            $("#downlog").html("Down: " + mouseX + " / " + mouseY);
        }

        $("#canvas").mousedown(function(e) {
            handleMouseDown(e);
        });

    </script>

在这段代码中,我通过鼠标点击检测坐标。 我想围绕这个坐标绘制一个圆圈,当我点击圆圈时,做一些事情(例如,打开google.com)

注意:我在html 4和区域地图中使用jquery执行此操作,但我在画布中没有任何想法。

2 个答案:

答案 0 :(得分:4)

我不知道你是想画一个圆圈,检测一​​个圆圈中是否有鼠标点击,或两者兼而有之。

画一个圆圈:

var context=canvas.getContext("2d");
ctx.beginPath();

//Draw a circle around a mouse click
//ctx.arc(x-position, y-position, radius, start-angle, end-angle);
ctx.arc(mouseX, mouseY, 30, 0, 2*Math.PI);
ctx.stroke();

在圆圈内检测鼠标点击:

//circleX and circleY are the coordinats of the center
var y = mouseY - circleY;
var x = mouseX - circleX;
var dist = Math.sqrt(y*y + x*x);

if (dist < circleRadius) {
  // Do whatever you want to do
}

答案 1 :(得分:0)

  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;
  var radius = 70;

  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  context.fillStyle = 'green';
  context.fill();
  context.lineWidth = 5;
  context.strokeStyle = '#003300';
  context.stroke();