在html5和javascript中的图像上画一个圆圈

kis*_*ore 7 javascript html5

HTML代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function start() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");

    var image = new Image();

    image.onload = function () {
        ctx.drawImage(image, 69, 50);
        //draw a circle
        ctx.beginPath();
        ctx.arc(100, 75, 10, 0, Math.PI * 2, true);
        ctx.stroke();
     };

    image.src = 'xy-coordinates.jpg';                 
  }
</script>
</head>
<img id="myImgId" alt="" src="xy-coordinates.jpg" />
<input type="button" value="submit" onclick="start()"> 
<canvas id="myCanvas" width="700" height="393"></canvas>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

单击按钮后,我正试图动态地在图像上画圆圈.

问题是在点击按钮后,我在屏幕上显示了一个额外的图像(带有圆圈),而不是在原始图像上绘图.

我的要求是在已经显示的图像上画一个圆圈.

更新

<script>

function Draw(){
var img = document.getElementById("theImg");
var cnvs = document.getElementById("myCanvas");

cnvs.style.position = "absolute";
cnvs.style.left = img.offsetLeft + "px";
cnvs.style.top = img.offsetTop + "px";

var ctx = cnvs.getContext("2d");
ctx.beginPath();
ctx.arc(250, 210, 10, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.stroke();
}


</script>

<img id='theImg' src='xy-coordinates.jpg'>
<input type='button' value='Draw' onclick='draw()' ><br>
<canvas id='myCanvas' width="700" height="393"></canvas>
Run Code Online (Sandbox Code Playgroud)

当在html标签中或在画布之后使用<br>时,图像和按钮r之间会有很大的距离.怎么纠正呢?

Ale*_*yan 11

您不需要再创建一个图像,因为画布实际上是一个图像.通过将其位置设置为绝对,左侧和顶部与源图像相同,将画布置于源图像的顶部:

var img = document.getElementById("myImgId");
var c = document.getElementById("myCanvas");
c.style.position = "absolute";
c.style.left = img.offsetLeft;
c.style.top = img.offsetTop;
Run Code Online (Sandbox Code Playgroud)

然后画进画布:

var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 10, 0, Math.PI * 2, true);
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)

更新:

function Draw(){
  var img = document.getElementById("theImg");
  var cnvs = document.getElementById("myCanvas");
  
  cnvs.style.position = "absolute";
  cnvs.style.left = img.offsetLeft + "px";
  cnvs.style.top = img.offsetTop + "px";
  
  var ctx = cnvs.getContext("2d");
  ctx.beginPath();
  ctx.arc(250, 210, 200, 0, 2 * Math.PI, false);
  ctx.lineWidth = 3;
  ctx.strokeStyle = '#00ff00';
  ctx.stroke();
}
Run Code Online (Sandbox Code Playgroud)
#draw-btn {
  font-size: 14px;
  padding: 2px 16px 3px 16px;
  margin-bottom: 8px;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <input id='draw-btn' type='button' value='Draw' onclick='Draw()' />
</div>
<img id='theImg' src='http://i.telegraph.co.uk/multimedia/archive/02351/cross-eyed-cat_2351472k.jpg'>
<canvas id='myCanvas' width='536px' height='536px'></canvas>
Run Code Online (Sandbox Code Playgroud)