2013-02-15 38 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>