App下載
首頁javascriptdrawing_settingsCanvas - 如何在剪裁區(qū)域內(nèi)繪制形狀

Canvas - 如何在剪裁區(qū)域內(nèi)繪制形狀

我們想知道如何在剪裁區(qū)域內(nèi)繪制形狀。

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    var ctx = document.getElementById('canvas').getContext('2d');
    ctx.fillRect(0, 0, 150, 150);
    // create a clipping path
    ctx.beginPath();
    ctx.moveTo(20, 20);
    ctx.lineTo(20, 130);
    ctx.lineTo(130, 130);
    ctx.lineTo(130, 20);
    ctx.clip();
    // backgroud in clipped area
    ctx.fillStyle = "#11c";
    ctx.fillRect(0, 0, 150, 150);
    // draw shapes inside clipped area
    ctx.translate(75, 90);
    ctx.fillStyle = '#f00';
    ctx.fillRect(-15, -40, 40, 40);
    ctx.fillRect(0, 0, 10, 10);
    ctx.fillRect(-25, 10, 60, 60);
});//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>