function math.round(number, decimals)
decimals = 10^(decimals or 0)
return math.floor(number * decimals + .5) / decimals
end
function setup()
parameter.color("rgba", color(155, 0, 155))
local width, height = 124, 124
canvas = {
x = 0,
y = 0,
width = width,
height = height,
zoom = 1,
img = image(width, height),
touches = {}
}
end
function draw()
noSmooth()
rectMode(CORNER)
spriteMode(CORNER)
noFill()
strokeWidth(1)
stroke(161, 141, 113, 255)
background(154, 175, 169, 255)
rect(canvas.x, canvas.y, canvas.width * canvas.zoom, canvas.height * canvas.zoom)
sprite(canvas.img, canvas.x, canvas.y, canvas.width * canvas.zoom, canvas.height * canvas.zoom)
noStroke()
fill(rgba)
rect(0, 0, WIDTH, 40)
end
function touched(touch)
-- Update touches
if #canvas.touches > 0 then
for n in ipairs(canvas.touches) do
if touch.id == canvas.touches[n].id then
canvas.touches[n].x = touch.x
canvas.touches[n].y = touch.y
canvas.touches[n].deltaX = touch.deltaX
canvas.touches[n].deltaY = touch.deltaY
canvas.touches[n].tapCount = touch.tapCount
end
end
end
-- Add touch
if touch.state == BEGAN then
if #canvas.touches < 2 then -- Max #touches allowed!
local n = #canvas.touches + 1
canvas.touches[n] = {
id = touch.id,
initX = touch.x,
initY = touch.y,
x = touch.x,
y = touch.y,
deltaX = touch.deltaX,
deltaY = touch.deltaY,
tapCount = touch.tapCount
}
if #canvas.touches > 1 then
onHold = true -- Lock drawing mode when using multitouch
end
end
return
end
-- Handle touches
if touch.state ~= BEGAN then
if touch.id == canvas.touches[1].id then
if #canvas.touches == 1 and not onHold then
-- Scale down touches from canvas to img bounds
local factor = vec2(canvas.width / (canvas.width * canvas.zoom), canvas.height / (canvas.height * canvas.zoom))
local position = vec2(math.round(canvas.touches[1].x * factor.x - canvas.x * factor.x), math.round(canvas.touches[1].y * factor.y - canvas.y * factor.y))
if canvas.touches[1].tapCount == 1 then
canvas.img:set(position.x, position.y, rgba) -- Draw pixel
elseif canvas.touches[1].tapCount == 2 then
canvas.img:set(position.x, position.y, color(0, 0, 0, 0)) -- Delete pixel
end
elseif #canvas.touches == 2 then
local pinch = vec2(canvas.touches[1].x, canvas.touches[1].y):dist(vec2(canvas.touches[2].x, canvas.touches[2].y))
canvas.zoom = canvas.zoom * pinch / (canvas.pinch or pinch)
canvas.pinch = pinch -- save measurement
canvas.x = canvas.x + canvas.touches[1].deltaX
canvas.y = canvas.y + canvas.touches[1].deltaY
end
end
end
-- Remove touch
if touch.state == ENDED then
for n in ipairs(canvas.touches) do
if touch.id == canvas.touches[n].id then
table.remove(canvas.touches, n)
end
end
if #canvas.touches == 0 then
onHold = nil
canvas.pinch = nil
end
end
end