draw a circle over a image in html5 and javascript

前端 未结 2 1067
花落未央
花落未央 2021-02-02 03:13

html code :





        
相关标签:
2条回答
  • 2021-02-02 03:30

    You don't need to create one more image because canvas in fact is an image by itself. Place your canvas on top of the source image by setting its position to absolute, left and top same as the source image:

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

    Then just draw into canvas:

    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>

    0 讨论(0)
  • 2021-02-02 03:46

    You are drawing one image on canvas, and second image with "img" tag (already displayed). you can't draw circle with canvas, on HTML tag.

    0 讨论(0)
提交回复
热议问题