deno-canvas的loadImage函数失效,求成功使用方法及案例
deno-canvas loadImage 使用问题解决:HTTP路径返回空对象、URL对象触发TypeError
问题描述
使用deno-canvas的loadImage函数时遇到两个问题:
- 传入HTTP图片路径字符串,返回空对象
- 传入
URL对象,触发错误:TypeError: url.startsWith is not a function
测试代码如下:
// Imports for canvas and image, see docs: // https://deno.land/x/canvas@v1.4.1 // https://github.com/DjDeveloperr/deno-canvas import { createCanvas, loadImage, } from 'https://deno.land/x/canvas@v1.4.1/mod.ts' // make sure above works: console.log('createCanvas', createCanvas) console.log('loadImage', loadImage) // create a url to a mozilla image. (Droping the url in browser showed it exists) const imgPath = 'https://developer.mozilla.org/assets/mdn_contributor.png' const imgUrl = new URL(imgPath) console.log('imgPath', imgPath) console.log('imgUrl', imgUrl) // load the image using http path. Result is empty object. let img = await loadImage(imgPath) console.log('img', img) // try with Url object. Fails with error img = await loadImage(imgUrl) console.log('img', img) // fails with this stack trace: // error: Uncaught (in promise) TypeError: url.startsWith is not a function // } else if (url.startsWith("http")) { // ^ // at loadImage (https://deno.land/x/canvas@v1.4.1/src/canvas.ts:23:18) // at file:///Users/owen/Dropbox/src/agentscript/tests/denoerror.js:25:13 // at eventLoopTick (ext:core/01_core.js:165:11)
解决方案及正确用法
1. 关键注意事项
loadImage仅接受字符串格式的URL:不要传入URL对象,因为函数内部直接调用了字符串的startsWith方法,URL对象不具备该方法,会触发TypeError。- 必须添加Deno网络权限:加载远程图片需要
--allow-net权限,否则Deno会阻止网络请求,导致图片加载失败返回空对象。
2. 可运行的示例代码
import { createCanvas, loadImage } from 'https://deno.land/x/canvas@v1.4.1/mod.ts'; async function loadAndDrawImage() { const imgUrl = 'https://developer.mozilla.org/assets/mdn_contributor.png'; // 传入字符串格式的URL const img = await loadImage(imgUrl); // 验证图片是否加载成功:打印宽高 console.log('图片宽度:', img.width); console.log('图片高度:', img.height); // 将图片绘制到画布 const canvas = createCanvas(img.width, img.height); const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); // 可选:将画布内容保存为本地图片(需要--allow-write权限) await Deno.writeFile('output.png', canvas.toBuffer()); console.log('图片已保存为output.png'); } loadAndDrawImage();
3. 运行命令
需要添加网络权限(若要保存文件则追加写入权限):
deno run --allow-net --allow-write your-file-name.ts
问题原因分析
- URL对象报错:deno-canvas v1.4.1的
loadImage函数实现中,直接对参数执行url.startsWith("http")判断,仅支持字符串类型的URL参数,传入URL对象会因缺少该方法报错。 - 空对象返回:Deno默认处于沙箱模式,未授权
--allow-net时,无法发起网络请求加载远程图片,最终返回空的Image实例。
内容的提问来源于stack exchange,提问作者backspaces
相关产品推荐
相关产品推荐

