draw a circle over a image in html5 and javascript

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

html code :





        
2条回答
  •  萌比男神i
    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;
    }

提交回复
热议问题