我正在尝试按照此示例加载灰度图像http://www.html5canvastutorials.com/advanced/html5-canvas-grayscale-image-colors-tutorial/。由于我的舞台有许多其他物品,我试图使用以下脚本:
var dImage1 = new Kinetic.Image({
drawFunc: function (canvas) {
var context2 = canvas.getContext();
var x = 0;
var y = 0;
context2.drawImage(imageObj, x, y);
var imageData = context2.getImageData(x, y, imageObj.width, imageObj.height);
var data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
data[i] = brightness;
data[i + 1] = brightness;
data[i + 2] = brightness;
}
context2.putImageData(imageData, x, y);
}
});
layer1.add(dImage1);
stage.add(layer1);
var imageObj = new Image();
imageObj.onload = function () {
drawImage(this);
};
imageObj.src = .....;
我收到此错误:TypeMismatchError。我要感谢你的建议,提前谢谢。
答案 0 :(得分:0)
我在你的代码中看到了几个陷阱......
首先,即使规范说它是可选的,你需要指定上下文模式(“2d”)
// must specify "2d"
var context2 = canvas.getContext("2d");
其次,在使用Kinetic.Image
之前,需要先完全加载图像所以将Kinetic.Image创建放在一个函数中并在imageObj.onload中调用它:
function makeKineticImage(){
var dImage1 = new Kinetic.Image({
drawFunc: function (canvas) {
var context2 = canvas.getContext("2d");
var x = 0;
var y = 0;
context2.drawImage(imageObj, x, y);
var imageData = context2.getImageData(x, y, imageObj.width, imageObj.height);
var data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
data[i] = brightness;
data[i + 1] = brightness;
data[i + 2] = brightness;
}
context2.putImageData(imageData, x, y);
}
});
layer1.add(dImage1);
}
stage.add(layer1);
// you must create your Kinetic.Image AFTER your image is loaded
var imageObj = new Image();
imageObj.onload = function () {
makeKineticImage();
};
imageObj.src = .....;