我试图制作一个小游戏,游戏中有几个不同颜色的形状,但我遇到了一个问题,我设法把这个问题归结为js代码:
const canvas = document.querySelector("canvas")
canvas.width = window.innerWidth;
canvas.height = window.innerHeight
const context = canvas.getContext("2d")
context.beginPath()
context.arc(canvas.width/2, canvas.height/2, 30, 0, 2*Math.PI, false)
context.fillStyle = 'blue'
context.fill()
context.beginPath()
context.fillRect(canvas.width/2, canvas.height/2, 100, 30)
context.fillStyle = 'green'
context.fill()
我创建了一个蓝色的圆圈,然后我想要创建一个绿色的矩形,但是由于任何原因,矩形会从圆圈中提取颜色,并被绘制成蓝色。
不按我想要的方式更改fillStyle的原因是什么?
发布于 2021-04-19 08:22:19
你需要改变通话顺序。首先设置fillStyle
,而不是fillRect
参见工作示例:https://jsfiddle.net/dw5u9etk/
const context = canvas.getContext("2d")
context.beginPath()
context.arc(canvas.width/2, canvas.height/2, 30, 0, 2*Math.PI, false)
context.fillStyle = 'blue'
context.fill()
context.beginPath()
context.fillStyle = 'green' // I only moved this line up
context.fillRect(canvas.width/2, canvas.height/2, 100, 30)
context.fill()
发布于 2021-04-19 09:21:41
fillRect()
在上下文子路径的之外绘制一个新的rect
,并直接填充它。
当您调用最后一个fill()
时,上下文的子路径为空。
您可以用rect()
代替此方法,
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d")
context.beginPath()
context.arc(canvas.width/2, canvas.height/2, 30, 0, 2*Math.PI, false)
context.fillStyle = 'blue'
context.fill()
context.beginPath()
context.rect(canvas.width/2, canvas.height/2, 100, 30)
context.fillStyle = 'green'
context.fill()
<canvas></canvas>
如果在调用beginPath()
+ fill()
之前移动fillStyle
赋值,则可以删除fillRect()
+fillRect()
调用
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d")
context.beginPath()
context.arc(canvas.width/2, canvas.height/2, 30, 0, 2*Math.PI, false)
context.fillStyle = 'blue'
context.fill()
context.fillStyle = 'green'
context.fillRect(canvas.width/2, canvas.height/2, 100, 30)
<canvas></canvas>
https://stackoverflow.com/questions/67158301
复制相似问题