canvas 颜色渐变

 部分语法:createLinearGradient(0,0,250,150)代表其实坐标(0,0)代表终点坐标(250,150)

   addColorStop(0.5,"green");代表0.5处渐变,颜色为green

<html>
    
    <head>
        <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
        <style type="text/css">
    
        </style>
        <script type="text/javascript">
         function draw(){
             var canvas =document.getElementById('myCanvas');
          
             var ctx=canvas.getContext('2d');
             var lingrad =ctx.createLinearGradient(0,0,250,150);
             lingrad.addColorStop(0,"blue");
             lingrad.addColorStop(0.5,"green");
             lingrad.addColorStop(1,"yellow");
             
             ctx.fillStyle=lingrad;
             ctx.fillRect(10,10,130,130);
         } 
         </script>
        <script type="text/css">
           canvas{border:1px solid black;}
        </script>>
    </head> <body >
        <input type="button" value="渐变" onclick="draw();">
        <p>
        <canvas id="myCanvas" width="150" height="150" ></canvas>
       
    </body>
   
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现图片渐变倒影可以通过以下步骤: 1. 在canvas中绘制原始图片。 2. 在canvas中创建一个渐变对象,用于创建倒影效果。 3. 将渐变对象应用到倒影区域的矩形中。 4. 使用clip()函数裁剪出倒影区域。 5. 将裁剪后的倒影区域翻转并绘制到canvas中,使其成为倒影效果。 以下是一个简单的实现示例代码: ```javascript // 获取canvas对象和上下文 var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); // 加载图片 var img = new Image(); img.src = 'example.jpg'; img.onload = function() { // 绘制原始图片 ctx.drawImage(img, 0, 0); // 创建渐变对象 var gradient = ctx.createLinearGradient(0, 0, 0, canvas.height / 2); // 添加渐变颜色 gradient.addColorStop(0, 'rgba(255, 255, 255, 0)'); gradient.addColorStop(1, 'rgba(255, 255, 255, 1)'); // 应用渐变到倒影区域 ctx.fillStyle = gradient; ctx.fillRect(0, canvas.height / 2, canvas.width, canvas.height / 2); // 裁剪出倒影区域 ctx.save(); ctx.beginPath(); ctx.rect(0, canvas.height / 2, canvas.width, canvas.height / 2); ctx.clip(); // 翻转倒影区域并绘制 ctx.translate(0, canvas.height); ctx.scale(1, -1); ctx.drawImage(img, 0, 0, canvas.width, canvas.height / 2); // 恢复之前的状态 ctx.restore(); }; ``` 在上述示例代码中,我们首先加载了一张示例图片,然后在canvas中绘制了原始图片。接着,我们创建了一个渐变对象并将其应用到倒影区域的矩形中。然后使用clip()函数裁剪出倒影区域,并对其进行翻转并绘制到canvas中,以实现倒影效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值