我一直在尝试用 Javascript 编写一个小型库,主要用于 Canvas drawImage() 方法。 该库的主要目的是传递数组值而不是传递单个值,例如:
// srcPos=[0,0] , size=[90,90], dstPos=[50,50]
function draw_image(context, image, srcPos, size, dstPos, size) {
context.drawImage(image, srcPos[0], srcPos[1], size[0], size[1], dstPos[0], dstPos[1], size[0], size[1]);
}
但是当我像这样调用这个函数 jzz 时,我得到了 Uncaught ReferenceError :
var canvas = document.getElementById("display"),
frame = canvas.getContext("2d");
var shipInfo = { center:[45, 45], size:[90, 90], radius: 35, angle:45 },
shipImage = new Image(),
pos = [40, 70];
shipImage.src = "ship.png";
function draw() {
draw_image(frame, shipImage, shipInfo.size, pos, shipInfo.size);
}
window.onload = function() {
draw();
}
是否可以像这样实现重写默认的drawImage()方法:
frame.draw_image(shipImage, srcPos, shipInfo.size, dstPos, shipInfo.size);
最佳答案
如果您想向 2d 上下文添加函数,JavaScript 可以通过原型(prototype)继承轻松实现这一点:您可以注入(inject) Context2D 对象来根据需要添加或更改其函数。
您可能想查看我在此处创建的小型 Canvas 库中对上下文所做的一些添加:https://github.com/gamealchemist/CanvasLib
有些人会说注入(inject)是邪恶的,但除非你在一艘大船上,否则我只会说:如果你使用一些图形库,尊重现有函数的语义,一切都应该没问题。如果你不使用库:尽一切努力!
因此,为了更具体地回答您的问题,您较短的绘制图像将给出:
CanvasRenderingContext2D.prototype.draw_image = function ( image,
srcPos, size,
dstPos, size) {
this.drawImage(image, srcPos[0], srcPos[1], size[0], size[1],
dstPos[0], dstPos[1], size[0], size[1]);
};
然后您可以在所有上下文中使用新函数:
var canvas = document.getElementById("display"),
frame = canvas.getContext("2d");
frame.draw_image( ... ) ;
请注意,您可以使用“矩形”对象,它是具有 4 个元素 x、y、w、h 的数组,并且会导致语法更短。
编辑:我在你的库中看到你想要旋转你的矩形。
首先,您不想重置转换。只需保存然后恢复即可。
我会尝试更接近这个的东西:
var x = dstPos[0],
y = dstPos[1],
halfWidth = dstSize[0]*0.5, // !! not src use >>1 if you know it's an int.
halfHeight = dstSize[1]*0.5, // !! not src ...
angleInRads = angle * Math.PI / 180;
this.save();
this.translate(x+halfWidth,y+halfHeight);
this.rotate(angleInRads);
this.drawImage(image
, center[0], center[1], srcSize[0], srcSize[1]
, -halfWidth, -halfHeight, dstSize[0],dstSize[1]);
this.restore();
关于javascript - 用 JavaScript 编写小型库时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22691591/