颜色和样式是通过strokeStyle和fillStyle两个属性修改的,它们的默认值都是black,strokeStyle表示画线(描边)用的样式,fillStyle表示填充用的样式,它们可以被赋予三种类型的值:纯色、渐变和模式。
纯色有以下三种赋值方法:
<body> <canvas id='c2d'>浏览器不支持canvas</canvas> <script> const canvas = document.getElementById('c2d'); if (canvas.getContext) { let ctx = canvas.getContext('2d'); ctx.fillStyle = "blue"; ctx.beginPath(); ctx.rect(0,0,20,20); ctx.fill(); ctx.fillStyle = "rgb(249,27,27)"; ctx.beginPath(); ctx.rect(20,20,20,20); ctx.fill(); ctx.fillStyle = "rgb(249,27,27, 0.5)"; ctx.beginPath(); ctx.rect(40,40,20,20); ctx.fill(); } </script></body>
渐变的颜色是通过CanvasGradient对象来表示的,它可以使用下面两个方法来创立:
addColorStop(offset,color)
offset用于设置控制点,取值范围【0,1】;color用于设置控制点的颜色。
示例:
<body> <canvas id='c2d'>浏览器不支持canvas</canvas> <script> const canvas = document.getElementById('c2d'); if (canvas.getContext) { let ctx = canvas.getContext('2d'); let lineGradient = ctx.createLinearGradient(20,20,100,150); lineGradient.addColorStop(0, 'red'); lineGradient.addColorStop(0.5, 'rgba(255,255,0,0.7)'); lineGradient.addColorStop(1, '#ff6d00'); ctx.fillStyle = lineGradient; ctx.beginPath(); ctx.arc(50,50,30,0,2*Math.PI); ctx.fill(); let radiaGradient = ctx.createRadialGradient(130,50,10,130,50,30); radiaGradient.addColorStop(0,'rgba(255,204,205,0.3)'); radiaGradient.addColorStop(0.5,'#ffff00'); radiaGradient.addColorStop(1,'#ff6d00'); ctx.fillStyle = radiaGradient; ctx.fillRect(100,20,60,60); } </script></body>
模式使用CanvasPattern对象来表示的,它使用createPattern方法来创立,语法如下:
createPattern(image,repetition);
参数中,image为CanvasImageSource类型,它可以是html中的img节点、video节点、canvas节点或者者CanvasRenderingContext2D对象。repetion为重复方式,它可以取下面4个值:
模式的用法就如同使用图片作为画笔绘图,其中repetition属性跟css中的background-repeat属性相似。
示例:
<body> <canvas id='c2d'>浏览器不支持canvas</canvas> <script> const canvas = document.getElementById('c2d'); if (canvas.getContext) { let ctx = canvas.getContext('2d'); var img = new Image(); img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png'; img.onload = function () { var pattern = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 400, 400); }; } </script></body>
假如我的博客对你有帮助、假如你喜欢我的博客内容,请 “点赞” “评论” “收藏” 一键三连哦!
听说 👉 点赞 👈 的人运气不会太差,每一天都会元气满满哦 嘿嘿!!! ❤️ ❤️ ❤️
大家的支持就是我坚持下去的动力。点赞后不要忘了👉 关注 👈我哦!