画布在手机上返回错误的颜色 [英] Canvas on mobile returns wrong colors
问题描述
将3种颜色的图片加载到移动Android设备(Samsung Galaxy S3)上的HTMLCanvas元素中。当检查使用的imageData中使用的颜色,我得到更多的颜色。当在普通PC上运行相同的代码时,我会得到确切的颜色和计数。
Im loading an image with 3 colors into a HTMLCanvas element on a mobile android device (Samsung Galaxy S3). When checking the used colors in the used imageData, I get a lot more colors. When running the same code on a usual PC, I get the exact colors and count.
示例代码:
function getColorsFromImageData (imageData) {
var colors = {};
var data = imageData.data;
for (var i = 0, len = data.length; i < len; i += 4) {
if (data[i+3] == 0) continue;
var rgb = data[i] + "," + data[i+1] + "," + data[i+2];
if (colors[rgb])
colors[rgb]++;
else
colors[rgb] = 1;
}
return colors;
};
function createColorElement (color, count) {
var elm = document.createElement("span");
elm.style.backgroundColor = "rgb(" + color + ")";
elm.className = "color";
elm.innerHTML = color + " (" + count + ")";
document.getElementById("colors").appendChild(elm);
}
window.onload = function() {
var canvas = document.getElementById("c");
var img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
var data = ctx.getImageData(0, 0, img.width, img.height);
var colors = getColorsFromImageData(data);
var count = 0;
for (var color in colors) {
createColorElement(color, colors[color]);
count++;
}
document.getElementById("count").innerHTML = count;
}
img.src = "test.png";
};
这里是一个小提琴: http://jsfiddle.net/d6714wdg/
如何在手机上获得准确的颜色?
How can I get the exact colors on mobile?
背景:我创建了一个基于HTMLCanvas的在线设计器。我需要确切的颜色值和没有抗锯齿,因为所有的颜色都需要符合一组与使用的羊毛颜色匹配的预定义颜色。
Background: I create an online designer based on HTMLCanvas. I need exact color values and no anti aliasing because all colors need to fit in a set of predefined colors matching the used wool color.
感谢任何帮助。 >
Thanks for any help.
推荐答案
您面对的问题是由于画布对 drawImage()
。
The issue you're facing is due to the canvas doing smoothing on drawImage()
by default.
这可以通过设置上下文的 imageSmoothingEnabled
属性设置为 false
。
This can be turned off by setting the context's imageSmoothingEnabled
property to false
.
此属性尚未稳定,您需要构造函数前缀:
This property is not yet stabilized and you'll need constructor prefixes :
ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
ctx.drawImage(img, 0, 0);
这篇关于画布在手机上返回错误的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!