table of Contents:
Article Directory
Problem analysis
When operating a drawImage()
function, it often canvas
happens that the call is normal, but the drawing is blank:
In this case, the reasons can be classified as:
- When the browser loads the picture, the picture has not been loaded yet, so start drawing
- The main reason is:
drawImage()
asynchronous function
Solution
-
drawImage()
Function, wait untilimg
the image specified in the label is loaded, and then start drawing, otherwise there will be no image -
Two loading methods can be declared:
img.onload = function() {drawImage()}
window.onload = function() {drawImage()}
-
Can be used
addEventListener('load', () => {drawImage()})
, can draw the image- The same goes for:
document.querySelector('#imgs').addEventListener('load', (event) => {drawImage()})
- The same goes for:
Example code
let img = document.getElementById('imgs');
// 会加载出图片
img.addEventListener('load', ()=> {
ctx.drawImage(img, 20, 20);
});
// 会加载出来图片
img.onload = () => {
ctx.drawImage(img, 20, 20);
}
effect:
Test sample
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
img <br />
<img id="imgs" width="240" height="240" src="../../img/show.jpg">
<hr />
canvas<br />
<canvas id="canvas" width="500" height="350"></canvas>
<script>
let c = document.getElementById('canvas');
let ctx = c.getContext('2d');
let img = document.getElementById('imgs');
// 会加载出图片
img.addEventListener('load', () => {
ctx.drawImage(img, 20, 20);
});
// 会加载出来图片
/* img.onload = () => {
ctx.drawImage(img, 20, 20);
} */
</script>
</body>
</html>