使用FillStyle()和RoundRect()创建不同颜色的圆角矩形。

huangapple go评论73阅读模式
英文:

Different Colors with FillStyle() and RoundRect()

问题

我想要两个填充的圆角矩形,每个矩形有不同的颜色,但它每次都给我最后一个颜色。

这是我的代码:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

ctx.fillStyle = "#00a6a4";
ctx.roundRect(10, 10, 100, 100, 10);
ctx.fill();
ctx.fillStyle = "#2e2e2e";
ctx.roundRect(110, 110, 100, 100, 10);
ctx.fill();

这是它给我的结果:

script result

英文:

So i wanted to have two filled rounded rectangle with a different color for each one but it give me the last color everytime

This is my code :

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth
canvas.height = window.innerHeight

// #2e2e2e
// #00a6a4

ctx.fillStyle = "#00a6a4";
ctx.roundRect(10, 10, 100, 100,10);
ctx.fill();
ctx.fillStyle = "#2e2e2e";
ctx.roundRect(110, 110, 100, 100,10);
ctx.fill();

This is what it give me :

script result

答案1

得分: 0

在第一次填充后调用ctx.beginPath()

第一次填充时,您正在填充一个矩形。但是在第二次填充时,您填充了两个矩形,因为您从未开始新的路径,所以您只是在第一个矩形上进行填充。

英文:

call ctx.beginPath() after the first fill.

On the first fill you are filling one rect. But then on the second fill, you are filling both rectangles because you never start a new path, so you are just filling over that first rect.

huangapple
  • 本文由 发表于 2023年7月12日 22:52:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定