在画布上绘制图像 [英] draw image on canvas
问题描述
我正在尝试将图像放在画布上.我阅读了以下教程
https://developer.mozilla.org/zh-CN /docs/Web/Guide/HTML/Canvas_tutorial/Using_images
并尝试做类似的事情
我的画布是<canvas id="canvas" width="400" height="400"></canvas>
并且我已经创建了函数
I am trying to put an image on a canvas. I read the following tutorial
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images
and tried to do something similar to it
my canvas is <canvas id="canvas" width="400" height="400"></canvas>
and I have created the function
function putImage(){
var img = new Image();
img.src = "./path.png";
var ctx = document.getElementById('canvas').getContext('2d');
ctx.drawImage(img,8,8);
}
,但是图像没有出现在画布上. 我已经打印了图像路径并且它是正确的,因此我能够消除此问题. 有什么建议吗?
but the image is not appearing on the canvas. I have printed the image path and it is correct, so I was able to eliminate this issue. any suggestions?
谢谢
推荐答案
根据教程,您应该像这样将ctx.drawImage()
包裹在img.onload
内
According to the tutorial, you're supposed to wrap your ctx.drawImage()
inside img.onload
like so
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
img.src = '/files/4531/backdrop.png';
}
我希望这会有所帮助.
这篇关于在画布上绘制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!