问题描述
我希望有人能告诉我我在这里做错了什么。
我正在尝试在画布上绘制图像。
图像是纹理图集(使用 texturePacker 创建)的一部分,因此有一个精灵表和一个随附的 JSON 文件:
{"frames": {
"cat.png":
{
"frame": {"x":2,"y":2,"w":128,"h":128},"rotated": false,"trimmed": false,"spriteSourceSize": {"x":0,"y":0,"sourceSize": {"w":128,"h":128}
},"hedgehog.png":
{
"frame": {"x":132,"tiger.png":
{
"frame": {"x":262,"h":128}
}},"Meta": {
"app": "https://www.codeandweb.com/texturepacker","version": "1.0","image": "animals.png","format": "RGBA8888","size": {"w":392,"h":132},"scale": "1","smartupdate": "$TexturePacker:SmartUpdate:9a29ce0a7220e3ca27b8044b48608e8d:06a75246a1a4b65f2beacae47a5e81d7:b00d48b51f56eb7c81e25100fcce2828$"
}
}
纹理图集由名为 assets.js 的文件预加载,该文件用于预加载游戏资产。我认为文件有点太大,无法在此处发布。
当我尝试使用 ctx.drawImage()
或 ctx.createPattern()
在画布上绘制预加载的图像时,出现错误:
TypeError: CanvasRenderingContext2D.createPattern: Argument 1 Could not be converted to any of:
HTMLImageElement,SVGImageElement,HTMLCanvasElement,HTMLVideoElement,ImageBitmap.
我应该能够通过以下方式访问精灵表上的单个图像:
`let anyImage = assets["anImage.png"]
所以,我的代码是这样的:
import { assets } from "../lib/assets.js";
import { makeCanvas } from "../lib/makeCanvas.js";
// load the files
assets
.load(["../images/animals.json","../images/animals.png"])
.then(() => setUp());
function setUp() {
let canvas = makeCanvas();
let ctx = canvas.ctx;
//Load an image to test that everything works
let catimage = new Image();
console.log(catimage);
catimage.addEventListener("load",loadHandler,false);
catimage.src = "../images/cat.png";
// try to use preloaded image fails with Type error
//ctx.drawImage(assets["tiger.png"],0);
// try another way of using preloaded image
// also fails with the same Type error
let tiger = assets["tiger.png"];
console.log(tiger);
let pattern = ctx.createPattern(tiger,"no-repeat");
ctx.fillStyle = pattern;
ctx.rect(0,64,64);
ctx.fill();
//The loadHandler to draw the catIamage
function loadHandler() {
ctx.drawImage(catimage,128,128);
}
}
注意:我没有包含 assets.js
或 makeCanvas.js
代码,因为我相信它们工作正常。但是可以在这里找到源代码:
assets.js
从 console.log(tiger) 我得到以下信息:
Object { frame: {…},rotated: false,trimmed: false,spriteSourceSize: {…},sourceSize: {…},source: img }
frame: Object { x: 262,y: 2,w: 128,… }
rotated: false
source: <img src="../images/animals.png">
sourceSize: Object { w: 128,h: 128 }
spriteSourceSize: Object { x: 0,y: 0,… }
trimmed: false
<prototype>: Object { … }
谁能看到我在这里做错了什么?似乎一切都按原样加载,但我似乎无法使用这些资产。
提前致谢,非常感谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)