有没有办法读取画布特定点的颜色?
就像是:
getColor :: Canvas -> Point -> Color
我检查了Graphics.UI.Threepenny.Canvas的文档,但找不到任何功能。也许我只是没看到,因为我使用 Haskell 的时间不长。
如果您对我有任何提示,请告诉我。
非常感谢,克莱姆
编辑:感谢 Heinrich Apfelmus 的回答,我能够编写一个可行的解决方案并希望分享它以防有人需要相同的功能。当然,如果您使用它并进行调整,请随时分享:)
import qualified Graphics.UI.Threepenny as UI
import Graphics.UI.Threepenny.Core
import Codec.Picture.Types
-- to UI (PixelRGB8) is also possible just change from fst to snd after the return
getCanvCol :: UI.Canvas -> UI.Point -> UI (UI.Color)
getCanvCol canvas (x,y) = do
-- str returns a string with comma separated values i.e. "255,0,255"
str <- callFunction $ ffi ("(%1.getContext('2d').getImageData(%2,%3,1,1).data[0])+\
\\",\"+(%1.getContext('2d').getImageData(%2,%3,1,1).data[1])+\
\\",\"+(%1.getContext('2d').getImageData(%2,%3,1,1).data[2])")
canvas x y
return $ fst $ tripleToCol $ lsToRGB $ wordsWhen (==',') str
where
-- could also use splitOn
wordsWhen :: (Char -> Bool) -> String -> [String]
wordsWhen p s = case dropWhile p s of
"" -> []
s' -> w : wordsWhen p s''
where (w, s'') = break p s'
-- take a list of strings and make a triple of ints
lsToRGB :: [String] -> (Int,Int,Int)
lsToRGB (a:b:c:xs) = (read a, read b, read c)
lsToRGB _ = (0,0,0)
-- make a triple of Int to Color needed
tripleToCol :: (Int,Int,Int) -> (UI.Color, PixelRGB8)
tripleToCol (r,g,b) = ((UI.RGB r g b),(PixelRGB8 r' g' b'))
where (r',g',b') = (fromIntegral r,fromIntegral g,fromIntegral b)