我正在尝试缓存可与canvas.drawImage()一起使用的对象,以显示图像,但只绘制一次。我一直收到此错误,我尝试了一些在线找到的答案,例如:canvasObject.get(0) and canvasObject[0] and unwrap(canvasObject)
,然后将它们放入绘制上下文中,但是这些都不起作用。我找不到任何东西。希望有人可以提供帮助。这是我的代码:
var canvas = full canvas that cached drawings should draw to
var temp = {};
var h = heightOfGridSquare;
var w = widthOfGridSquare;
var canvasElementForCache = document.createElement('canvas');
canvasElementForCache.width = w * 2; // so that i can draw pictures larger then single grid square
canvasElementForCache.height = h * 2;
var cachedCanvas = canvasElementForCache.getContext(ctx);
// cache drawing in app object
var cacheDrawing = function ( name ){
app.cache[name] = objectRepo[name](cachedCanvas);
};
var objectRepo = {
someObjectName: function (canv) {
var m = temp.coordinates;
canv.fillStyle = "rgba(0,0,200,0.9)";
canv.fillRect(m.x + 25, m.y + 25,50, 50); // random filler (x and y are coordinates defined in the draw object funciton )
return canv;
},
};
var drawObejectAtCoordinates = function ( x, y ) {
var px = ( x - ( w / 2 ));
var py = ( y + ( h / 2 ));
if ( app.cache[name] === undefined ){
temp.coordinates = { x:px, y:py };
cacheDrawing(name);
}
// drawing on actual canvas
canvas.drawImage( app.cache[name], px, py );
};
var render = function () {
drawObejectAtCoordinates( coordinateX, coordinateY );
// this is just a place holder, my actual code is very long and has different rendering methods..
// just know that it is being rendered ( not super important though since the error occurs at drawImage not render )
window.requestAnimationFrame(render);
}
为了简洁起见,为简洁起见,我已将一小部分更改了..但没有任何遗漏与该问题有关。如果有人可以提供帮助,我将不胜感激!
错误消息是:
TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement.
当我控制台记录缓存的 Canvas 对象的内容时,它看起来像这样:
CanvasRenderingContext2D { canvas: <canvas>, globalAlpha: 1, globalCompositeOperation: "source-over", strokeStyle: "#41471d", fillStyle: "#ff8800", shadowOffsetX: 0, shadowOffsetY: 0, shadowBlur: 0, shadowColor: "rgba(0, 0, 0, 0)", mozCurrentTransform: Array[6] }
这是一个jsFiddle示例:https://jsfiddle.net/1krgqeq7/3/
最佳答案
这里有许多问题使这些代码难以遵循:
1)您正在以一种令人困惑的方式重用变量cachedDrawing
(它是元素还是函数?)
2)您使用一个名为temp
的变量,它通常是一种代码味道,尤其是当您不靠近其声明使用它时(在代码示例中不存在)。还不清楚为什么您的 stash 地点在那里。
3)您使用了大量描述性变量名,但除了temp之外,还使用了非描述性的'obj'
但是,对您的问题的回答(与上面的1相关)是您正在传递上下文,而不是其来源的 Canvas 。不要重新分配该var,而是将其传递到缓存中。
使用更具描述性的变量名,例如cachedCanvas
是 Canvas ,而cachedCtx
是其上下文,这样的问题将更容易发现。