gpt4 book ai didi

javascript - HTML5 Canvas - 如何在 Canvas 中的图像上绘制矩形

转载 作者:太空狗 更新时间:2023-10-29 15:25:54 25 4
gpt4 key购买 nike

实际上,我可以使用 img.onload 函数来完成。我从 'HTML5 Canvas - How to Draw a line over an image background? 得到的东西'.但是我需要在不使用 onload 函数的 img 的情况下绘制图像,如下所示:

    var imagePaper = new Image();


imagePaper.onload = function(){


context.drawImage(imagePaper,100, 20, 500,500);
};

imagePaper.src = "images/main_timerand3papers.png";
}

但我希望能够在 Canvas 上绘制矩形,只需将 img src 附加到 Canvas 上方,就像:

<body>  
<img id="scream" src="my.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<canvas id="myCanvas" width="500" height="500" >
Your browser does not support the HTML5 canvas tag.</canvas>

但我无法在 Canvas 中的 img 上画线,img 正在绘制或形状隐藏在后面。这是我的完整代码:

 <!DOCTYPE html>  
<head>
<title>Playing YouTube video on HTML5 canvas</title>
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width" />
<style type="text/css">
body {
margin: 0px;
padding: 0px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>
<body>
<img id="scream" src="my.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<canvas id="myCanvas" width="500" height="500" >
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,10,10);
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.beginPath();
context.rect(188, 50, 200, 100);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
</script>
</body>
</html>

最佳答案

因为您不是在等待图像先加载。在您的脚本中添加一个window.onload()

<script>
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = document.getElementById('scream');

context.drawImage(img, 10, 10);

context.beginPath();
context.rect(188, 50, 200, 100);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
}
</script>

发生的事情是它试图在加载图像之前绘制图像,执行 window.onload 将在加载整个文档(例如图像)后调用代码。否则它可能不显示图像或绘制出线条。

关于javascript - HTML5 Canvas - 如何在 Canvas 中的图像上绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26902084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com