Turtle library color fill

color fill function

Using Turtle can not only draw lines, but also fill the drawn closed lines.

- set fill color: fillecolor(r, g, b)
- start filling: begin_fill()
- end filling: end_fill()

Exercise 1

Take the exercise code of the last drawing and initialize a fill color first. Then, use begin_fill() before drawing each figure and end_fill() after drawing. This will give you a fill effect. Only the graphics that fill the upper right and lower left corners are selected here.

import turtle as t
import random as r


def pink():
    color = (1, r.random(), 1)
    return color


def randomrange(min, max):
    return min + (max- min)*r.random()


def moveto(x, y):
    t.penup()
    t.goto(x, y)
    t.pendown()


def heart(r, a):
    factor = 180
    t.seth(a)
    t.circle(-r, factor)
    t.fd(2 * r)
    t.right(90)
    t.fd(2 * r)
    t.circle(-r, factor)


t.setup(800, 800, 200, 200)
t.speed(9)
t.pensize(1)
t.penup()

for i in range(20):
    t.goto(randomrange(-300, 300), randomrange(-300, 300))
    t.begin_fill()
    t.fillcolor(pink())
    heart(randomrange(10, 50), randomrange(0, 90))
    t.end_fill()

moveto(400, -400)

t.done()

operation result

write picture description here

Exercise 2

Draw a set of randomly distributed, random sizes and different shades of hearts.

import turtle as t
import random as r


def randomcolor():
    color = (r.random(), r.random(), r.random())
    return color


def pink():
    color = (1, r.random(), 1)
    return color


def randomrange(min, max):
    return min + (max- min)*r.random()


def moveto(x, y):
    t.penup()
    t.goto(x, y)
    t.pendown()


def heart(r, a):
    factor = 180
    t.seth(a)
    t.circle(-r, factor)
    t.fd(2 * r)
    t.right(90)
    t.fd(2 * r)
    t.circle(-r, factor)


# set canvas dimension
t.setup(800, 800, 200, 200)
t.speed(9)


t.pensize(1)
t.pencolor(randomcolor())
t.fillcolor(randomcolor())


t.penup()
for i in range(20):
    t.goto(randomrange(-300, 300), randomrange(-300, 300))
    t.begin_fill()
    t.fillcolor(pink())
    heart(randomrange(10, 50), randomrange(0, 90))
    t.end_fill()

moveto(400, -400)

t.done()

operation result

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324504305&siteId=291194637