0

如何使用 Javascript 或 HTML5 以圆形显示整个图像。我尝试了下面的代码,但使用此代码,只有部分图像会被转换为圆形。如何使整个显示器呈圆形?

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
      #myCanvas {
        border: 1px solid #9C9898;
      }
    </style>

    <script type="text/javascript" >

</script>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <div id="myCanvas"></div>
    <script>
     var ctx = document.getElementById('myCanvas').getContext("2d");
      ctx.arc(100,100, 50, 0, Math.PI*2,true); // you can use any shape
      ctx.clip();

        var img = new Image();
        img.addEventListener('load', function(e) {
        ctx.drawImage(this, 0, 0, 200, 300);
 }, true);
img.src="images/hospital_review_profile_placeholder.png";


    </script>
  </body>
</html>
4

1 回答 1

0

您可以调整图像大小和重新定位图像以适合您的圆圈,而不是使用 ctx.clip()。

这是将您的图像调整为适合圆圈的最大尺寸的代码。

然后代码将调整大小的图像正确定位在圆圈中。

这是一个小提琴 --- http://jsfiddle.net/m1erickson/s6MzZ/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
    $(function(){

        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");

        var radius=50;      // circle radius
        var fullWidth=200;  // actual width of image in pixels
        var fullHeight=300; // actual height of image in pixels
        var centerX=100;    // center X coordinate of the circle
        var centerY=100;    // center Y coordinate of the Circle

        // the image must be resized to fit into the circle
        // Call CalcResizedImageDimensions() to get the resized width/height
        var size=CalcResizedImageDimensions(radius,fullWidth,fullHeight);

        var rectX=centerX-size.width/2; // the X coordinate of the resized rectangle
        var rectY=centerY-size.height/2 // the Y coordinate of the resized rectangle

        ctx.beginPath();
        ctx.arc(centerX,centerY,radius,0,Math.PI*2,true);

        // I illustrate with just a rectangle
        // you would drawImage() instead
        ctx.rect(rectX,rectY,size.width,size.height);
        ctx.stroke();

        function CalcResizedImageDimensions(r,w,h){
            var d=2*r;
            var newH=(d*h)/Math.sqrt(w*w+h*h);
            var newW=w/h*newH;
            return({width:newW,height:newH});
        }

    }); // end $(function(){});
</script>

</head>

<body>

<canvas id="canvas" width=200 height=200></canvas>


</body>
</html>
于 2013-02-15T20:16:25.687 回答