我正在尝试创建一个可以与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.
当我在控制台上记录缓存的画布对象的内容时,它看起来像这样:
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/
答案 0 :(得分:0)
There are a number of issues here that make this code rather difficult to follow:
1) You are reusing the variable cachedDrawing
in a confusing way (is it an element or a function?)
2) You use a variable named temp
which is usually a code smell, especially when you don't use it close to its declaration (not present in the code sample). Its also not clear why your stashing coords in there.
3) You use a fair number of descriptive variable names but in addition to temp you also use the rather non-descript 'obj'
But the answer to your question (related to 1 above) is that you are passing a context, not the canvas it was gotten from. Don't reassign that var and pass it into the cache instead.
Problems like this will likely be easier to spot with more descriptive variable names like cachedCanvas
being a canvas and cachedCtx
being its context.