如何将图像添加到画布
我正在尝试使用 HTML 中的新 canvas 元素。
我只是想将图像添加到画布上,但由于某种原因它不起作用。
我有以下代码:
HTML
<canvas id="viewport"></canvas>
CSS
canvas#viewport { border: 1px solid white; width: 900px; }
JS
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
context.drawImage(base_image, 100, 100);
}
图像存在,我没有收到 JavaScript 错误。图像只是不显示。
这一定是我错过的非常简单的事情......
I'm experimenting a bit with the new canvas element in HTML.
I simply want to add an image to the canvas but it doesn't work for some reason.
I have the following code:
HTML
<canvas id="viewport"></canvas>
CSS
canvas#viewport { border: 1px solid white; width: 900px; }
JS
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
context.drawImage(base_image, 100, 100);
}
The image exists and I get no JavaScript errors. The image just doesn't display.
It must be something really simple I've missed...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要等到图像加载后才能绘制。请尝试以下操作:
即在图像的 onload 回调中绘制图像。
You need to wait until the image is loaded before you draw it. Try this instead:
i.e. draw the image in the onload callback of the image.
这是在画布上绘制图像的示例代码 -
在上面的代码中 selectedImage 是一个输入控件,可用于在系统上浏览图像。
有关在画布上绘制图像同时保持宽高比的示例代码的更多详细信息:
http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html
here is the sample code to draw image on canvas-
In the above code selectedImage is an input control which can be used to browse image on system.
For more details of sample code to draw image on canvas while maintaining the aspect ratio:
http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html
您必须使用 .onload
原因如下
如果您在创建画布后首先加载图像,则画布将无法传递所有图像数据绘制图像。所以你需要首先加载图像附带的所有数据,然后你可以使用drawImage()
You have to use .onload
Here's Why
If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()
context.drawImage提供了三种方式供您选择。
或者您可以参考 w3school-canvas drawImage 的说明。
context.drawImage provide three ways for your choise.
Or you can reference explains from w3school-canvas drawImage.
就我而言,我弄错了函数参数,它们是:
如果您期望它们是,
您将把图像放置在画布之外,其效果与问题中描述的效果相同。
In my case, I was mistaken the function parameters, which are:
If you expect them to be
you will place the image just outside the canvas with the same effects as described in the question.