使用canvas和javascript来读取图像的像素颜色 [英] use canvas and javascript to read the pixel colors of an image
本文介绍了使用canvas和javascript来读取图像的像素颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否可以使用画布和javascript来扫描图片的某些像素颜色,并使用它们来制作地图。
例如:
找到#ff0000
并将其设置为地图上的数字1,并设置#000000
到2,依此类推:
I would like to know if it is possible to use canvases and javascript to scan an image for certain pixel colors and use them to make a map.
e.g:
find #ff0000
and set it to the number 1 on the map and set #000000
to 2 and so on to make a map like:
var map = [
[1,1,1,1,1],
[1,0,0,0,1],
[1,0,2,0,1],
[1,0,0,0,1],
[1,1,1,1,1]
];
所以基本上我想知道如何获取代码读取图像,
So basically i want to know how to get the code to read an image and find the colors i want it to search for and then plot them out in a variable
推荐答案
这是一个好的开始。
var zeroFill = function(num, padding) {
return Array(padding + 1 - (num + '').length).join('0') + num;
}
var hexColorsToId = {
'ff0000': 1,
'000000': 2
/* ... */
},
map = [],
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
image = new Image;
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
var data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
for (var i = 0; i < data.length; i += 4) {
var red = zeroFill(data[i].toString(16), 2),
green = zeroFill(data[i + 1].toString(16), 2),
blue = zeroFill(data[i + 2].toString(16), 2),
hex = red + green + blue;
if (hexColorsToId.hasOwnProperty(hex)) {
map.push(hexColorsToId[hex]);
}
}
}
image.src = '/img/logo.png';
这篇关于使用canvas和javascript来读取图像的像素颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文