簡體   English   中英

使用Javascript或HTML5以圓形顯示整個圖像

[英]Display whole image in circulr shape using Javascript or HTML5

如何使用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>

無需使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM