2

キャンバスの特定のポイントの色を読み取る方法はありますか?

何かのようなもの:

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

1 に答える 1