-- Simple paint on love2d function love.load() love.graphics.setDefaultFilter("nearest", "nearest") font = love.graphics.newFont(20) scrw = love.graphics.getWidth() scrh = love.graphics.getHeight() canvas = love.graphics.newCanvas(scrw, scrh) bg = make_checker_canvas(scrw, scrh) love.graphics.setCanvas(canvas) love.graphics.clear(0, 0, 0, 0) love.graphics.setCanvas() mx, my = 0, 0 req_clear_canvas = false req_export = false msg_timer = 0 msg_str = "" end function love.update(dt) mx, my = love.mouse.getPosition() if req_clear_canvas then -- clear canvas req_clear_canvas = false msg_timer = 0.75 msg_str = "Clear canvas" love.graphics.setCanvas(canvas) love.graphics.clear(0, 0, 0, 0) love.graphics.setCanvas() end if love.mouse.isDown(1) then -- draw brush love.graphics.setCanvas(canvas) love.graphics.setColor(0, 1, 0, 1) love.graphics.circle("fill", mx, my, 8) love.graphics.setCanvas() end if req_export then -- export canvas req_export = false msg_timer = 0.75 local filename = os.date("%Y-%m-%d_%H-%M-%S") .. ".png" if export_canvas(canvas, filename) then msg_str = "Export " .. filename else msg_str = "Can not export." end end if msg_timer > 0 then msg_timer = msg_timer - dt if msg_timer <= 0 then msg_timer = 0 end end end function love.draw() love.graphics.setCanvas() love.graphics.clear(0, 0, 0, 1) -- draw bg love.graphics.setColor(1, 1, 1, 1) love.graphics.draw(bg) -- draw canvas love.graphics.draw(canvas) -- draw cursor love.graphics.setColor(1, 1, 1, 1) love.graphics.circle("line", mx, my, 8) -- draw text love.graphics.setFont(font) love.graphics.setColor(1, 1, 1, 1) if msg_timer > 0 then love.graphics.print(msg_str, 2, 40) end love.graphics.print("C)lear S)ave", 10 * 10, 2) love.graphics.print("FPS: " .. tostring(love.timer.getFPS()), 2, 2) end function love.keypressed(key, isrepeat) if key == "escape" then -- ESC key to exit love.event.quit() elseif key == "s" and msg_timer == 0 then req_export = true elseif key == "c" then req_clear_canvas = true end end function export_canvas(canvas, filename) local imagedata = canvas:newImageData() local filedata = imagedata:encode("png") local filepng = io.open(filename, "wb") if filepng ~= nil then filepng:write(filedata:getString()) filepng:close() return true end return false end function make_checker_canvas(w, h) local cnavas = love.graphics.newCanvas(w, h) cnavas:renderTo( function() local start = true local sz = 8 local x, y for y = 0, (h - 1), sz do local fg = start for x = 0, (w - 1), sz do local c = fg and 0.6 or 0.4 love.graphics.setColor(c, c, c, 1) love.graphics.rectangle("fill", x, y, sz, sz) fg = not fg end start = not start end end ) return cnavas end