简体   繁体   中英

Canvas - new shapes get wrong colors

I was trying to make a small game in which there are a few shapes with different colors, but I ran into a problem which I have managed to boil down to this js code:

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()

I create a blue circle and then I want to create a green rectangle, but the rectangle for whatever reason takes the color from the circle and is drawn as blue.

What could be the reason for not changing the fillStyle as I want it to?

You need to change the order of the calls. First set the fillStyle and than the fillRect

See working example: 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() draws a new rect outside of the context's subpath and fills it directly.

When you call the last fill() the context's subpath is empty.

You could replace this method with rect() instead,

 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>

or you could remove the beginPath() + fill() calls if you move the fillStyle assignment before the call to 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM