如何将图像添加到画布 [英] How to add image to canvas
本文介绍了如何将图像添加到画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 HTML 中的新画布元素.
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.
我有以下代码:
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 错误.图片就是不显示.
The image exists and I get no JavaScript errors. The image just doesn't display.
一定是我遗漏了一些非常简单的东西......
It must be something really simple I've missed...
推荐答案
需要等到图片加载完毕再绘制.试试这个:
You need to wait until the image is loaded before you draw it. Try this instead:
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}
}
即在图片的onload回调中绘制图片.
i.e. draw the image in the onload callback of the image.
这篇关于如何将图像添加到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文