我想知道是否有人可以帮助我弄清楚如何使用 HTML5 Canvas 和 JavaScript 在图像上绘制对象?
我写了一个例子来说明我的问题(只要你有一个名为 choc.jpg 的图像可用,它应该可以工作)。我希望香蕉对象出现在 JPEG 上,但事实并非如此。我是 HTML5 和画布的新手,非常感谢您指出正确的方向。非常感谢你的帮助!
<!DOCTYPE HTML>
<script>
window.onload=function() {
var testcanvas=document.getElementById("bananaDesign");
var testcontext=testcanvas.getContext('2d');
//set a background image
/* if I comment out this section no image appears and the banana gets drawn. How do I get banana to go over image? */
var importedImg = new Image();
importedImg.src = 'pictures/choc.JPG';
importedImg.onload = function(){
testcontext.drawImage(importedImg, 10, 10);
};
//draw a banana
testcontext.fillStyle = "#FFA824";
testcontext.beginPath();
testcontext.moveTo(62,20);
testcontext.lineTo(80,20); //2
testcontext.lineTo(80,30); //3
testcontext.lineTo(90,50); //4
testcontext.lineTo(80,85); //5
testcontext.lineTo(45,95); //6
testcontext.lineTo(40,80); //7
testcontext.lineTo(60,60); //8
testcontext.lineTo(60,30); //9
testcontext.fill();
}
</script>
<canvas id="bananaDesign" width="500" height="600" style="border: 5px red solid">
<p>Your browser does not display HTML5 canvas. Please update to view this design.</p>
</canvas>