Draw a circle above the image in html5 and javascript

html code:

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

I try to draw a circle on the image dynamically as soon as I press the button.

The problem is that after clicking the button, I get an additional image (with a circle pattern) displayed on the screen, instead of drawing the original image.

My requirement is to draw a circle on an image that is already displayed.

UPDATED

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

when <. used in the html tag before or after the canvas, there is a huge distance between the image and the r button of any tags that I place there. how to fix it?

+4
source share
2 answers

, - . , , , :

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

:

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

UPDATE:

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();
}
#draw-btn {
  font-size: 14px;
  padding: 2px 16px 3px 16px;
  margin-bottom: 8px;
}
<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>
Hide result
+6

, "img" ( ). , HTML.

0

All Articles