HTML5 画布 - 如何在画布中的图像上绘制矩形
HTML5 Canvas - How to draw rectangle over image in canvas
实际上,我可以使用img.onload
函数来做到这一点。我从"HTML5 Canvas - 如何在图像背景上画一条线?"得到的东西。但是我需要在不使用img
的情况下绘制图像onload
函数如下所示:
var imagePaper = new Image();
imagePaper.onload = function(){
context.drawImage(imagePaper,100, 20, 500,500);
};
imagePaper.src = "images/main_timerand3papers.png";
}
但是我希望能够在画布上绘制矩形,只需在画布上方附加img src,就像:
<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>
但是我无法在画布上的 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>
因为您没有等待图像先加载。在script
中添加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
将在整个文档加载(例如图像)后调用代码。否则,它可能不显示任何图像或将其绘制出线条。
我尝试了使用window.onload()的相同方法,直到我使用Edge浏览器尝试使用它Microsoft它才有效。对我有用的解决方案是将onload处理程序附加到图像,例如:
image.onload = function ()
{
context.drawImage(image, 0, 0);
}
然后它完美地工作了。
相关文章:
- 用图像而不是颜色填充对象(将图像绘制到画布上)
- 仅使用Chrome进行慢速图像绘制
- 将 SVG 图像绘制到 CanvasRenderingContext2D 中
- 为什么我不能将图像绘制到画布中
- 将许多新图像绘制到画布时内存泄漏
- Javascript - 加载GIF冻结,同时将图像绘制到画布(Phonegap/Cordova)
- 画布:绘制图像而不是将图像绘制到画布
- 将图像绘制到<画布>
- 在浏览器中识别完整的图像绘制
- 画布图像绘制失败
- 将图像绘制到画布上
- 如何在画布上为运动图像绘制多条路径
- 将图像绘制到画布有时不显示任何东西
- 修剪透明背景的图像绘制在画布与PHP或javascript
- Javascript将图像绘制在彼此之上
- 我可以将数组值插入到画布的图像绘制函数中吗?
- 画布上的图像绘制比原始尺寸大
- 画布图像绘制不工作
- 将预先加载的图像绘制到画布中
- javascript从缓冲区(nodejs/socket.io)将图像绘制到html中