JS Canvas 矩形特效:凸起、凹陷、雕刻与双色边框
要在 JS Canvas 中实现矩形的凸起、凹陷和雕刻效果,并使对边两条的颜色不一样,可以使用以下步骤:
- 创建 Canvas 元素并获取其上下文:
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
- 设置 Canvas 的宽度和高度,以适应所需的矩形大小:
canvas.width = 400;
canvas.height = 200;
- 绘制矩形的凸起效果。可以使用
fillStyle属性设置矩形的颜色,使用fillRect方法绘制矩形:
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 300, 100);
- 绘制矩形的凹陷效果。可以使用
fillStyle属性设置矩形的颜色,使用fillRect方法绘制矩形:
ctx.fillStyle = 'blue';
ctx.fillRect(70, 70, 260, 60);
- 绘制矩形的雕刻效果。可以使用
strokeStyle属性设置矩形的颜色,使用lineWidth属性设置线条宽度,使用strokeRect方法绘制矩形的边框:
ctx.strokeStyle = 'green';
ctx.lineWidth = 10;
ctx.strokeRect(50, 50, 300, 100);
- 使对边两条的颜色不一样。可以使用
createLinearGradient方法创建一个线性渐变对象,设置渐变的起始和结束点,使用addColorStop方法添加颜色停止点,然后使用strokeStyle属性将渐变对象设置为矩形的颜色:
var gradient = ctx.createLinearGradient(50, 50, 350, 150);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.strokeStyle = gradient;
完整的代码示例如下:
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 200;
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 300, 100);
ctx.fillStyle = 'blue';
ctx.fillRect(70, 70, 260, 60);
ctx.strokeStyle = 'green';
ctx.lineWidth = 10;
ctx.strokeRect(50, 50, 300, 100);
var gradient = ctx.createLinearGradient(50, 50, 350, 150);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.strokeStyle = gradient;
你可以将 Canvas 元素添加到页面中,如:
document.body.appendChild(canvas);
这样就可以在页面上看到矩形的凸起、凹陷和雕刻效果,并使对边两条的颜色不一样。
原文地址: https://www.cveoy.top/t/topic/pVi1 著作权归作者所有。请勿转载和采集!