Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
function drawImage(imgURL) {
    return new Promise(resolve => {
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.addEventListener('load', e => {
            const canvas = document.createElement('canvas')
            const ctx = canvas.getContext('2d')
            // 將canvas尺寸設定與來源圖片一樣
            const width = img.width
            const height = img.height
            canvas.width = width
            canvas.height = height
            // 繪圖
            ctx.drawImage(img, 0, 0)
            resolve(canvas)
         })
        img.src = imgURL
    })
}
const imgURL = 'http://juliandance.org/wp-content/uploads/2016/01/RedApple.jpg'
drawImage(imgURL).then(canvas => {
    const width = canvas.width
    const height = canvas.height
    const ctx = canvas.getContext('2d')
    const imageData = ctx.getImageData(0, 0, width, height)
    
    console.log(imageData)
    // [object ImageData] {
    //     data: [object Uint8ClampedArray],
    //     height: 456,
    //     width: 400
    // }
    const imageBuffer = imageData.data
    console.log(imageBuffer)    // [object Uint8ClampedArray]
    let red, green, blue, alpha;    // 定義各顏色的暫存變數
    let arg
    // 注意這裡的 i, 每次迭代時為 i += 4, 而非 i++
    for (let i = 0; i < imageBuffer.length; i += 4) {
        // 在imageBuffer之中每4個元素分別代表著每個像素的red, green, blue, alpha數值(0 ~ 255)
        red   = imageBuffer[i]
        green = imageBuffer[i + 1]
        blue  = imageBuffer[i + 2]
        alpha = imageBuffer[i + 3]
        // 將畫布中每個像素的rgb值設定為rgb平均值,能使圖片灰階化
        arg = (red + green + blue) / 3
        imageBuffer[i] = arg 
        imageBuffer[i + 1] = arg
        imageBuffer[i + 2] = arg
        imageBuffer[i + 3] = alpha
    }
    ctx.putImageData(imageData, 0, 0)
    document.body.appendChild(canvas)
})
Output

This bin was created anonymously and its free preview time has expired (learn why). — Get a free unrestricted account

Dismiss x
public
Bin info
anonymouspro
0viewers