[英]Canvas - new shapes get wrong colors
我试图制作一个小游戏,其中有几个形状不同的 colors,但我遇到了一个问题,我设法归结为这个 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 的原因可能是什么?
您需要更改调用顺序。 首先设置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()
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>
或者,如果在调用fillRect()
之前移动fillStyle
分配,则可以删除beginPath()
+ fill()
调用:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.