为啥我的图像不会显示在 javascript 画布上?
Posted
技术标签:
【中文标题】为啥我的图像不会显示在 javascript 画布上?【英文标题】:Why wont my image show on a javascript canvas?为什么我的图像不会显示在 javascript 画布上? 【发布时间】:2021-03-30 21:22:27 【问题描述】:这是我这个类的构造函数中的代码
this.canvas = document.getElementById("myCanvas");
this.canvasContext = this.canvas.getContext('2d');
this.canvasContext.font = "45px Arial";
this.canvas.onshow = function ()
console.log("here!");
window.renderer.updateDimesions();
这是我基于其质量的单位的方法。目前它是一个原型代码。除了渲染图片外,一切正常。错误消息是“未捕获的类型错误:无法读取未定义的属性'drawImage'”
drawUnits = function(SceneGraph,uType)
var aLength = window.SceneGraph.getLength();
var offset = 0;
for(var i = 0; i < aLength; i ++)
var length = SceneGraph.get(i).getLength();
var width = SceneGraph.get(i).getWidth();
var price = SceneGraph.get(i).getPrice();
var type = SceneGraph.get(i).getType();
var description = SceneGraph.get(i).getDescription();
var expanded = SceneGraph.get(i).getExpanded();
console.log(length,width,price,type,description);
if(expanded)
this.canvasContext.font = "45px Arial"
this.canvasContext.fillText(length + "x" + width,0, (i * 50) + 50 + offset)
this.canvasContext.fillText(price + "$",670, (i * 50) + 50 + offset)
this.canvasContext.beginPath();
this.canvasContext.rect(0, (i*50) + offset, 774, 50);
this.canvasContext.stroke();
//row with price and size
this.canvasContext.fillText("PICTURE",0, (i * 50 ) + 120)
this.canvasContext.font = "15px Arial"
this.wrapText(this.canvasContext,description,258,(i * 50)+ 70,516,20) //html5canvastutorials.com. 2020. HTML5 Canvas Text Wrap Tutorial. [online] Available at: <https://www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/> [Accessed 21 December 2020].
this.canvasContext.font = "30px Arial"
this.canvasContext.fillText("Click van to reserve unit",258, (i * 50) + 175)
this.canvasContext.font = "45px Arial"
var van = new Image();
van.src = "images/perfec1.jpg";
van.onload = function()
this.canvasContext.drawImage(van,100,100);
// this.canvasContext.fillText("VAN",650, (i * 50) + 175)
offset = 150; // keep at end
【问题讨论】:
代码似乎不完整。缺乏一些结构。可以展示完整的代码吗? 还在您的onload
回调中添加一个console.log 以验证加载的图像。您也应该添加一个onerror
回调并记录是否有错误。
我添加了整个代码
我还添加了一个 console.log 并且图像确实加载了。
这个里面的 onload 指的是 Image (van) 对象。请看***.com/questions/9696200/…
【参考方案1】:
我通过将 onload 更改为事件侦听器来修复它
van.addEventListener('load', e =>
this.canvasContext.drawImage(van,516, (i* 50) - 18);
);
【讨论】:
事件监听器没有解决这个问题。您已使用箭头函数表达式developer.mozilla.org/en-US/docs/Web/javascript/Reference/… 修复它。换句话说,如果您将 e => 替换为 function() 它将无法再次工作。您可以通过执行 van.onload = () => this.canvasContext.drawImage(van,516, (i* 50) - 18); 来修复它,以使您的原始事件侦听器方法正常工作。以上是关于为啥我的图像不会显示在 javascript 画布上?的主要内容,如果未能解决你的问题,请参考以下文章