我正在尝试通过构建自己的游戏引擎来自学游戏引擎的内容。当我说基本的基本游戏引擎时,那没有错字。到目前为止,我只有一个简单的文本加载器,而我正在开发一个图像加载器。即使使用 .onload = function 样式技术,我也无法让我的图像出现在 Canvas 中。事实上,我总是在加载图像时遇到问题,我只是为了拉屎和咯咯地笑,制作了一个加载四个短视频的视频加载器,制作并附加了视频标签和保存它们的 div,而且仍然,图像让我发疯了伙计们和女孩们!卧槽!任何帮助,但更重要的是,洞察力对于新手来说是无价的,并且有助于尝试理解而不是在不理解的情况下进行复制。提前致谢。
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
function drawText(context, pxSize, fontStyle, color, text, x, y){
context.font = pxSize + 'px ' + fontStyle;
context.fillStyle = color;
context.fillText(text, x, y);
}
function drawHero(src, sourceX, sourceY, sourceWidth, sourceHeight, x, y, height, width){
var hero = {
image: new Image(),
src: src,
sourceX: sourceX,
sourceY: sourceY,
sourceWidth: sourceWidth + 'px',
sourceHeight: sourceHeight + 'px',
x: x,
y: y,
width: width + 'px',
height: height + 'px'
};
hero.image.onload = function(){
context.drawImage(hero.image, hero.sourceX, hero.sourceY, hero.sourceWidth,
hero.sourceHeight, hero.x, hero.y, hero.width, hero.height);
}
hero.image.src = src;
}
drawHero("sonic.png" , "sonic1", 0, 0, 85, 119, 10, 10, 85, 119);
最佳答案
您将 hero.width
和 hero.height
定义为字符串,这会导致错误,因为 context.drawImage
需要一个数字高度和宽度。
去掉 width: width + "px"
和 height: height + "px"
并替换为 width: width
和height: 高度
.
编辑:刚刚意识到您对 hero.sourceWidth
和 hero.sourceHeight
做了同样的事情。
编辑 2:刚刚意识到您将 10 个参数传递给 drawHero
而它只需要 9 个。您应该删除 "sonic1"
。
编辑 3:您也将 context.drawImage
的参数命令错了。
您可能想阅读以下内容:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage .
用这个:
context.drawImage(hero.image, hero.x, hero.y, hero.width, hero.height, hero.sourceX, hero.sourceY, hero.sourceWidth, hero.sourceHeight);
祝你的游戏引擎好运!
关于javascript - 尝试构建一个基本的基本游戏引擎,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084175/