2013-02-15 53 views
0

如何使用Javascript或HTML5以circulr形状显示整个图像。我尝试了下面的代码,但是通过这段代码,只有图像的一部分会被转换成圆形。我怎样才能让整个显示器呈圆形?使用Javascript或HTML5以circulr形状显示整个图像

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

回答

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>