javascript - 在 html5 canvas 中绘制图像的一部分

标签 javascript jquery html canvas html5-canvas

我正在尝试在我的 Canvas 中绘制第一个绿色坦克,但我认为我的代码中遗漏了一些东西

jsfiddle :

draw: function () {
    tankImg.onload = function () {
        ctx.drawImage(tankImg, this.Pos * this.w, 0, this.w, this.h, this.x, this.y, this.w, this.h);
    };
}

谁能帮帮我?

最佳答案

好的,首先非常感谢 fiddle - 让一切变得简单十亿倍。

您的代码中有 两个 个错误 - 第一个是 tankImg.onload 函数。 onload 函数仅触发一次 - 当图像首次加载时。

你想要的是 tankImg.complete,它在加载时返回 true,否则返回 false。

其次,您不能为 y 属性分配“ch - this.h”,因为“this”直到您完成定义后才被定义。您可以做的是在绘图代码中设置 y 值。

第三,在 javascript 中你不能做 var cw, ch = 400;

 $(document).ready(function () {
     var cw = 400;
     var ch = 400;
     var ctx = $("#MyCanvas")[0].getContext("2d");
     var tankImg = new Image();
     tankImg.src = "http://oi62.tinypic.com/148yf7.jpg";
     var Fps = 60;
     var PlayerTank = {
         x: cw / 2,
         w: 84,
         h: 84,
         Pos: 2,
         draw: function () {
             ctx.drawImage(tankImg, this.Pos * this.w, 0, this.w, this.h, this.x, ch - this.h, this.w, this.h);
         }
     };

     var game = setInterval(function () {
         if (tankImg.complete) {
             PlayerTank.draw();
             PlayerTank.x++;
         }
     }, 1000 / Fps);
 });

这是完成的 jsfiddle带有奖励运动的乐趣。

编辑:Ken 处理 .onload 的版本要好得多。

关于javascript - 在 html5 canvas 中绘制图像的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21623756/

相关文章:

javascript - 将 HTML 元素翻译成 Jquery 但看不到它们

javascript 图像平移 'blocking' 导航链接并使 div 元素不透明

php - 多个带有值的仪表

javascript - Jquery 评分星级无法正常工作

javascript - 在控制台中修改本地 javascript 变量

javascript - 与 DOM 元素作斗争

javascript - 什么查询选择器找不到与另一个数组中的任何项目匹配的任何数组项目?

javascript - 如何限制手动输入时html5数字输入的最大值

jquery - 切换内联样式背景色

javascript - BxSlider:最后一张幻灯片上为 "next"-> 跳回第一张幻灯片?