带圆角的帆布drawimage

tbu*_*aru 6 javascript canvas coverflow

我在我的网站上使用这个封面流程脚本,我不知道如何输出带圆角的画布.

这是绘制图像的代码

ctx.drawImage(image, cropLeft, cropTop, wid-2*cropLeft, hei-2*cropTop, 0, 0, newWidth, newHeight);
Run Code Online (Sandbox Code Playgroud)

我使用arc()或arcTo()函数阅读了一些教程,但我们都没有使用图像作为对象.

UPDATE1:我看到drawimage()只有以下绘图参数:•与原件尺寸和构图相同的图像•从原件调整大小的图像•从原件裁剪的图像

所以,我想,通过画布绘制带圆角的图像是不可能的.

mar*_*rkE 17

您可以使用context.clip()绘制在圆角矩形内剪裁的图像

在此输入图像描述

首先绘制一个带圆角的矩形(无需笔触或填充):

  // draw a rounded rectangle

  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.lineTo(x + width - radius, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  ctx.lineTo(x + width, y + height - radius);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  ctx.lineTo(x + radius, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  ctx.lineTo(x, y + radius);
  ctx.quadraticCurveTo(x, y, x + radius, y);
  ctx.closePath();
Run Code Online (Sandbox Code Playgroud)

然后调用context.clip,这将导致所有未来的绘图在rect中被剪裁

  ctx.clip();
Run Code Online (Sandbox Code Playgroud)

最后,在该矩形内绘制图像,您的图像将被剪裁成圆形.

  ctx.drawImage(img,10,10,102,77);
Run Code Online (Sandbox Code Playgroud)

这是示例代码和小提琴:http: //jsfiddle.net/m1erickson/FLaee/

<!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 img=new Image();
    img.onload=function(){
        ctx.save();
        roundedImage(10,10,102,77,10);
        ctx.clip();
        ctx.drawImage(img,10,10,102,77);
        ctx.restore();
    }
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/sky-bg2.jpg";


    function roundedImage(x,y,width,height,radius){
      ctx.beginPath();
      ctx.moveTo(x + radius, y);
      ctx.lineTo(x + width - radius, y);
      ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
      ctx.lineTo(x + width, y + height - radius);
      ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
      ctx.lineTo(x + radius, y + height);
      ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
      ctx.lineTo(x, y + radius);
      ctx.quadraticCurveTo(x, y, x + radius, y);
      ctx.closePath();
    }

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

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • @SephReed是的,“取消剪辑”并不那么明显。在`ctx.save`和`ctx.restore`之间包装`ctx.clip`。保存将保存初步未剪切的上下文属性,而还原将通过还原这些初步属性来“取消剪辑”。 (2认同)