使用相对文件路径将图像添加到JavaScript画布 [英] adding image to Javascript canvas using relative file path

查看:115
本文介绍了使用相对文件路径将图像添加到JavaScript画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得有一个非常简单的方法来做到这一点,但我找不到它。我有一个图像,其相对路径到我的 clientscript.js 文件是 ./ images / orig经典pokemon frame.png 。我想在画布上绘制这个代码片段最后一行的文本:

  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

文本显示在画布上, 。更改尺寸或x和y坐标不起作用。任何帮助是赞赏。



编辑:将文件路径更改为 images / origclassicpokemonframe.PNG ,现在图片显示在firefox的画布不是铬。
help ????



另一个编辑:我可以在控制台中看到chrome和firefox的HTTP请求加载它只是很好,但不知何故只是不想画在画布上。

解决方案

上下文不是全局变量。因此,在'onload'函数中使用它不在其范围之内。



如果您的src会在< img> 元素中工作, >

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. 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. Any help is appreciated.

EDIT: Changed the filepath to images/origclassicpokemonframe.PNG and now the image shows on canvas in firefox, but not 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.

解决方案

context isn't a global variable. As such, using it in the 'onload' function is out of it's scope.

There was nothing wrong with your src if it would work in an <img> element.

这篇关于使用相对文件路径将图像添加到JavaScript画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆