您的位置:首页 > Web前端 > HTML5

HTML5中canvas实现矩形颜色渐变

2016-06-12 18:03 671 查看
<!--<!DOCTYPE> 声明必须是 HTML 文档的第一行,位于 <html> 标签之前。-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset = utf-8">
<title>HTML5</title>
<script type="text/javascript" charset = "utf-8">
//这个函数将在页面完全加载后调用
window.onload = function() {
draw();
};
function draw(grad) {
var canvas = document.getElementById('c1');
if (!canvas||! canvas.getContext ) { return false; }
var ctx = canvas.getContext('2d');
ctx.beginPath();
/* 指定渐变区域 */
var grad  = ctx.createLinearGradient(0,0, 0,140);
/* 指定几个颜色 */
grad.addColorStop(0,'rgb(216, 9, 0)');    //
grad.addColorStop(0.5,'rgb(225, 255, 0)'); // 绿
grad.addColorStop(1,'rgb(42, 231, 0)');  //hong
/* 将这个渐变设置为fillStyle */
ctx.fillStyle = grad;
/* 绘制矩形 */
ctx.rect(10,10,20,140);
ctx.fill();
// ctx.fillRect(0,0, 140,140);
}

</script>
</head>
<body>
<canvas width = "400" height = "200" id = "c1" style = "border:black 1px solid;">
<!--如果浏览器不支持则显示如下字体-->
提示:你的浏览器不支持<canvas>标签
</canvas>
</body>
</html>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: