简体   繁体   English

使用相对文件路径将图像添加到Javascript画布

[英]adding image to Javascript canvas using relative file path

I feel like there is a very simple way to do this, yet I can't find it. 我觉得有一个非常简单的方法可以执行此操作,但是我找不到它。 I have an image whose relative path to my clientscript.js file is ./images/orig classic pokemon frame.png . 我有一个形象,其相对路径我clientscript.js文件./images/orig classic pokemon frame.png I want to draw it on the canvas, around the text that is drawn on the very last line of this code snippet: 我想在此代码段的最后一行上绘制的文本周围,将其绘制在画布上:

function render(context) {
    context.fillStyle = 'black';
    context.strokeStyle = 'black';
    context.save();
    var imgFrame = new Image();
    imgFrame.src = './images/origclassicpokemonframe.png';
    imgFrame.onload = function(){
        context.drawImage(imgFrame, 0, 0, 30,30);
    };
    context.font = "24px Early GameBoy";
    context.fillText("What? _____", 10, canvasHeight-44); //20 padding plus 24 line height

The text shows up on the canvas, but the frame never does. 文本显示在画布上,但框架从不显示。 Changing the dimensions or the x and y coordinates does not make a difference. 更改尺寸或x和y坐标没有区别。 Any help is appreciated. 任何帮助表示赞赏。

EDIT: Changed the filepath to images/origclassicpokemonframe.PNG and now the image shows on canvas in firefox, but not chrome. 编辑:将文件路径更改为images/origclassicpokemonframe.PNG ,现在图像显示在Firefox中的画布上,而不显示在chrome中。 help???? 救命????

Another edit: I can see in the console on both chrome and firefox that the HTTP request is loading it just fine but somehow it just doesn't want to draw on the canvas. 另一个编辑:我可以在chrome和firefox的控制台上看到HTTP请求正在很好地加载它,但是以某种方式它只是不想在画布上绘制。

context isn't a global variable. context不是全局变量。 As such, using it in the 'onload' function is out of it's scope. 因此,在“ onload”功能中使用它已超出其范围。

There was nothing wrong with your src if it would work in an <img> element. 如果您的src可在<img>元素中使用,则没有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM