• 欢迎来到本站,本站主要做程序员相关技术、博客、笔记,如果喜欢本网站那么赶紧使用Ctrl+D 收藏吧!
  • 如果有任何疑问,可以在下方文章下方留下你的评论~

Example of using HTML canvas createlineargradient() method

技术文章 8个月前 (10-21) 1次浏览 0个评论

Browser support

Internet Explorer 9, Firefox, opera, chrome, and safari support the createLinearGradient() Method.

Note: the <canvas> element is not supported in Internet Explorer 8 and earlier.

Definition and Usage

The createlineargradient() method creates a linear gradient object.

Gradients can be used to fill rectangles, circles, lines, text, and so on.

Tip: use this object as the value of the strokestyle or fillStyle property.

Tip: use the addcolorstop() method to specify different colors and where to locate colors in the gradient object.

JavaScript syntax: context.createLinearGradient (x0,y0,x1,y1);

Example 1

Defines a black to red gradient (left to right) as a fill pattern for the rectangle:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>chinapenpal.com</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
CHINA PEN PAL
</canvas>
<script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    var grd=ctx.createLinearGradient(0,0,150,0);
    grd.addColorStop(0,"black");
    grd.addColorStop(1,"red");
    ctx.fillStyle=grd;
    ctx.fillRect(0,0,200,100);
</script>
</body>
</html>

Example of using  HTML canvas createlineargradient() method

Example 2 addColorStop

The addcolorstop() method specifies the color and position in the gradient object.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>chinapenpal.com</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
CHINA PEN PAL
</canvas>
<script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    var grd=ctx.createLinearGradient(0,0,150,0);
    grd.addColorStop(0,"black");
    grd.addColorStop(0.2,"red");
    ctx.fillStyle=grd;
    ctx.fillRect(0,0,200,100);
</script>
</body>
</html>

Example of using  HTML canvas createlineargradient() method

Example 3

Define a gradient from black to red to white as the fill pattern of the rectangle:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CHINA PEN PAL</title>
</head>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
HELLO WORLD
</canvas>
<script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    var grd=ctx.createLinearGradient(0,0,170,0);
    grd.addColorStop(0,"black");
    grd.addColorStop(0.5,"red");
    grd.addColorStop(1,"white");
    ctx.fillStyle=grd;
    ctx.fillRect(20,20,150,100);
</script>

</body>
</html>

Example of using  HTML canvas createlineargradient() method


中国笔友, 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Example of using HTML canvas createlineargradient() method
喜欢 (0)
发表我的评论
取消评论
表情 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址