javascript - 尝试构建一个基本的基本游戏引擎

标签 javascript canvas html5-canvas game-engine drawimage

我正在尝试通过构建自己的游戏引擎来自学游戏引擎的内容。当我说基本的基本游戏引擎时,那没有错字。到目前为止,我只有一个简单的文本加载器,而我正在开发一个图像加载器。即使使用 .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.widthhero.height 定义为字符串,这会导致错误,因为 context.drawImage 需要一个数字高度和宽度。

去掉 width: width + "px"height: height + "px" 并替换为 width: widthheight: 高度.

编辑:刚刚意识到您对 hero.sourceWidthhero.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/

相关文章:

javascript - 在更改之前检查样式?

javascript - window.matchMedia 的 AddEventListener 无法正常工作 javascript

html - 在 Canvas 上绘制的文本抗锯齿效果不佳

javascript - 当用户单击时,如何阻止我的文本在数组中循环?

javascript - 在 Canvas 上绘制(渐进式)油漆飞溅

javascript - HTML Canvas 保存在 mysql 数据库上

javascript - 如何在同一索引处输出不同的数组javascript

javascript - 双簧管 : Nothing happens after JSON response

JavaScript getImageData Canvas

javascript - 图像动画功能在 fabric js 中不起作用?