如何使用
HTML5画布元素绘制具有如下图所示的渐变效果的矩形?
编辑:感谢您的所有反馈.是的,我已经尝试了很多方法.例如,我可以使用@Loktar建议的createRadialGradient方法吗?以下是一些示例代码:
<html> <head> <title>test</title> <script type="application/x-javascript"> function draw() { var canvas = document.getElementById("canvas"),ctx = canvas.getContext("2d"); var grad1 = ctx.createRadialGradient(50,50,50); grad1.addColorStop(0,'rgba(255,252,1)'); grad1.addColorStop(1,'rgba(68,205,37,1)'); ctx.fillStyle = grad1; ctx.fillRect(0,100,100); } </script> </head> <body onload="draw();"> <div> <canvas id="canvas" width="100" height="100"></canvas> </div> </body> </html>
但结果并不是我想要的:
这应该通过GDI提供的PathGradientBrush等方法轻松完成.
我不确定HTML5 canvas元素是否可行.
解决方法
您可以尝试使用线性渐变和剪裁的组合.
Demo.代码:
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var outerColor = 'rgba(68,1)'; var innerColor = 'rgba(255,1)'; var w = 200; var h = 50; canvas.width = w; canvas.height = h; function gradient(dir) { var grad = ctx.createLinearGradient(dir[0],dir[1],dir[2],dir[3]); grad.addColorStop(0,outerColor); grad.addColorStop(0.5,innerColor); grad.addColorStop(1.0,outerColor); return grad; } // idea: render background gradient and a clipped "bow" function background() { ctx.fillStyle = gradient([0,h]); ctx.fillRect(0,w,h); } function bow() { ctx.save(); ctx.beginPath(); ctx.moveTo(0,0); ctx.lineTo(w,h); ctx.lineTo(w,0); ctx.lineTo(0,h); ctx.clip(); ctx.fillStyle = gradient([0,0]); ctx.fillRect(0,h); ctx.restore(); } background(); bow();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。